543. 二叉树的直径

    技术2022-07-11  74

    // 最大直径不一定经过root int maxVal; public int diameterOfBinaryTree(TreeNode root) { if (root == null) return 0; getNodeCountonDiameter(root); return maxVal - 1; } // 返回直径上的总节点个数 public int getNodeCountonDiameter(TreeNode root) { if (root == null) return 0; int left = getNodeCountonDiameter(root.left); int right = getNodeCountonDiameter(root.right); maxVal = Math.max(left + right + 1, maxVal); return Math.max(left, right) + 1; }
    Processed: 0.010, SQL: 9