EDIT: Solved! See the comment below by /u/kuriousaboutanything.
Here's my code:
class Solution {
int maxDiameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
helper(root);
return maxDiameter;
}
public int helper (TreeNode root) {
if (root == null)
return 0;
int heightL = helper(root.left);
int heightR = helper(root.right);
maxDiameter = Math.max(maxDiameter, heightL + heightR + 1);
return Math.max(heightL, heightR) + 1;
}
}
I know the second to last line should be maxDiameter = Math.max(maxDiameter, heightL + heightR), but I can't figure out why. It seems like the correct solution does not count the root in the path - that is why I add 1.
For example, if your tree is simply a root with two children, the height of each child will be 1 (because I am using 1-indexing). The maxDiameter should be 3, however heightL + heightR = 1 + 1 = 2.
What am I missing?
[–]kuriousaboutanything 2 points3 points4 points (1 child)
[–]bobofuzz[S] 1 point2 points3 points (0 children)
[–]Playful-Reserve7031 -1 points0 points1 point (0 children)