Diameter of Binary Tree
Compute the longest path in one DFS by returning subtree heights and updating a running best.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Diameter of Binary Tree
Input: [1, 2, 3, 4, 5]
Output: 3
Longest path can be 4 - 2 - 1 - 3 (3 edges).
Input: [1, 2, 3, 4, 5, 6, 7]
Output: 4
One longest path: 4 - 2 - 1 - 3 - 7.
Constraints
- Nodes in the tree are in range [1, 10^4].
- Node values are not important for this problem.
Core Formula
candidate(node) = leftHeight + rightHeight
Run one DFS. At each node update best=max(best, candidate), and return height=1+max(left, right).
How to Think
Ask each child for height
Every recursive call returns one integer: subtree height.
Compute local candidate
Path through current node uses one branch from left + one branch from right.
Return height upward
Parent only needs your best downward branch: 1 + max(left, right).
Dry Run
Code
Complexity
Time
O(n)
Each node is processed exactly once.
Space
O(h)
Recursion stack depth equals tree height.
Interview Uses
Balanced Binary Tree
You already compute left/right heights at every node, so balance checks are a natural extension.
Height of Binary Tree
Diameter helper is fundamentally a height DFS with one extra candidate update.
Maximum Path Sum
Same tree DP pattern: compute child contributions and update a global answer.
N-ary Tree Diameter
Generalize by keeping top two child heights instead of just left/right.
Ready to watch candidate updates live?
Open the visualizer and inspect leftHeight, rightHeight, and best at each node.