TreesAnimated
Diameter of Binary Tree
The longest path is max over nodes of left height + right height.
Time
O(n)
Extra space
O(h)
Use it for
Longest path between any two nodes.
How it works
- The diameter is the number of edges on the longest path between any two nodes. It may not pass through the root.
- At every node, the longest path that bends at that node has length (left height + right height).
- Compute heights bottom-up and track the largest such sum.
- O(n).
Watch it run
Loading animation…