FAANGPrep Sprint
Diameter of Binary Tree
Measure the longest path, counted in edges, between any two nodes of a binary tree. The path does not have to pass through the root.
Examples
Path is [4,2,1,3] or [5,2,1,3], length 3 (3 edges).
Problem Understanding
The diameter of a tree is the number of edges on the longest path between any two nodes.
Crucially, the path does NOT need to pass through the root. It could be entirely contained within the left or right subtree.
Algorithm Strategy
We use Post-Order DFS.
At any node, the longest path that bends at that node has left + right edges, where left and right are the heights of its two subtrees. The longest path overall can bend at any node, not only the root.
So:
- Return Value: the height of the subtree,
max(left, right) + 1— a parent can extend only one side. - Side Effect:
best = max(best, left + right).
Interactive Visualization
h = HEIGHT RETURNED · GREEN = LONGEST PATH SO FAR
best = 0
best
0
Diameter
—
call stack
No calls in progress
best = 0
Next
Call height on the root, 1
Tree
Heights appear under nodes as they return. The longest path found so far is drawn in green, and it moves only when some node’s left + right beats it — often at a node that is not the root.
