Binary Tree Diameter
The diameter is the longest path between any two nodes in the tree. A key observation is that for each node, a candidate diameter passes through that node and has length equal to the height of its left subtree plus the height of its right subtree. A postorder traversal computes subtree heights bottom-up while maintaining the maximum diameter.
Use postorder traversal.
Height is computed once for every node.
Time complexity: O(n).
Auxiliary recursion space: O(h).
If diameter is defined in nodes rather than edges, add one to the edge-based result for a non-empty tree.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience