The longest path between any two nodes need not pass through the root, which is what trips people up. The clean answer is one DFS that returns each node's height while updating a global best as it goes. First, nail down whether diameter counts edges or nodes.
Compute the diameter of a binary tree
The longest path between any two nodes need not pass through the root, which is what trips people up. The clean answer is one DFS that returns each node's height while updating a global best as it goes. First, nail down whether diameter counts edges or nodes.
Updated Aug 2026 · Grounded in real Forward Deployed Engineer interview loops and written to a senior-engineer editorial bar.
This is the gateway to the harder 'maximum path sum' problem, and it teaches the same pattern: a DFS that returns one value upward (height) while side-effecting a global maximum that can bridge through any node. The trap is thinking the diameter must run through the root. The other trap is the edges-versus-nodes ambiguity; a candidate who asks about it before coding signals care, because it shifts the answer by exactly one.
No comments yet — be the first to share your approach.
