Given the root of a binary tree, return the length of the diameter — the longest path between any two nodes (measured in edges). The path may or may not pass through the root.
root = [1,2,3,4,5]3root = [1,2]1node == null → return 0L = depth(node.left)R = depth(node.right)diameter = max(diameter, L + R)1 + max(L, R) to parentThe diameter path may not pass through the root. By maintaining a global variable updated at every node, we capture the widest path anywhere in the tree. Post-order guarantees both L and R heights are known before computing L+R — children inform parents, not the reverse.
For every node, you could compute the heights of its two subtrees separately. Recomputing heights again and again makes that O(n²). We can get every height and every candidate in a single pass.
Write a function that returns the height of a node, counted in nodes. For a node, ask for the left height and the right height. The longest path that bends at this node uses left plus right edges. Update a global best with left plus right. Then return 1 plus the larger of the two heights to the parent.
Return height, but record the diameter on the side. Left height plus right height is the path that bends at this node.
Run the animation above on your own input, or watch the 1:58 video explanation of Diameter of Binary Tree with a dry run and Java code.