Diameter of Binary Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #543
The diameter of a binary tree is the number of edges on the longest path between any two nodes. The path doesn't have to pass through the root. Return it.
Examples
text
[1, 2, 3, 4, 5] → 3 (4 → 2 → 1 → 3, or 5 → 2 → 1 → 3)
[1, 2] → 1
[1, 2, null, 3, 4, 5, null, null, 6] → 4 (entirely in the left subtree)Hints
- The longest path "bending" at a node has length height(left) + height(right).
- Compute heights bottom-up and keep a running maximum of left + right.
Approach
Write h(node) returning the height in nodes (0 for null). At each node, the longest path through it uses h(left) + h(right) edges, so update a global best. Return 1 + max(h(left), h(right)) to the parent. One pass, O(n). This is the "global answer" trick: the recursion returns heights, while the diameter is tracked separately.
Complexity
Time: O(n). Space: O(h).
Python solution
def diameterOfBinaryTree(root):
best = 0
def h(node):
nonlocal best
if not node:
return 0
l, r = h(node.left), h(node.right)
best = max(best, l + r)
return 1 + max(l, r)
h(root)
return bestJavaScript solution
function diameterOfBinaryTree(root) {
let best = 0;
const h = (node) => {
if (!node) return 0;
const l = h(node.left), r = h(node.right);
best = Math.max(best, l + r);
return 1 + Math.max(l, r);
};
h(root);
return best;
}