Diameter of Binary Tree
Master this topic with zero to advance depth.
Diameter of Binary Tree
Find the length of the longest path between any two nodes in a tree.
Examples
Level I: Recursive DFS (Bottom-Up)
Intuition
The diameter of a tree at node is the maximum of:
- Depth of Left Subtree + Depth of Right Subtree.
- Diameter of Left Subtree.
- Diameter of Right Subtree. Using a bottom-up approach, we can calculate height and track the max diameter simultaneously.
Detailed Dry Run
Node(2): Left height=1, Right height=1. Diameter = 2. Max = 2. Return height=2.
Level II: Recursive Bottom-Up (Pair Result)
Intuition
Instead of using a global variable, each recursive call returns a pair: (height, diameter_so_far). This is a cleaner functional approach.
Diagram
Node(2) returns {Height: 2, Diameter: 2}
Node(3) returns {Height: 1, Diameter: 0}
Root(1) calc: max(2.H+3.H, 2.D, 3.D) -> max(3, 2, 0) = 3.Detailed Dry Run
DFS returns {h, d}. For null: {0, 0}. For leaf: {1, 0}. For 2: l={1,0}, r={1,0} -> {2, 2}. Final root returns {max_h, max_d}.
Level III: Optimal (Iterative Post-order)
Intuition
We can solve this iteratively by performing a Post-order traversal using a stack. We keep a Map to store the heights of nodes as we finish processing them. For each node, diameter = height(left) + height(right).
Logic
- Use a stack for post-order.
- Store computed heights in
Map<TreeNode, Integer>. height = 1 + max(h_left, h_right).diameter = h_left + h_right.
Detailed Dry Run
Stack processes leaves first, populating Map(leaf) = 1. Then Parent(2) sees l=1, r=1, Map(2)=2, MaxD=2. Root(1) sees Map(2)=2, Map(3)=1, MaxD=max(2, 3)=3.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.