Diameter of Binary Tree
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Diameter of Binary Tree
Find the length of the longest path between any two nodes in a tree.
Examples
Input: root = [1,2,3,4,5]
Output: 3
Approach 1
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.
⏱ O(N)💾 O(H)
Detailed Dry Run
Node(2): Left height=1, Right height=1. Diameter = 2. Max = 2. Return height=2.
Approach 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.⏱ O(N)💾 O(H)
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}.
Approach 3
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.
⏱ O(N)💾 O(N)
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.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.