Diameter of Binary Tree
Pattern: Depth, diameter and balance
The longest path between two nodes bends at some node: down its left side and down its right side. Compute each node's height; at each node, left height plus right height is the longest path bending there. The answer is the largest such sum, in edges.
The problem
Return the number of edges on the longest path between any two nodes. The path need not pass through the root.
[1, 2, 3, 4, 5] gives 3. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Where does the longest path turn?
- How long is the longest path that turns at a node?
- Does it always go through the root?
Hints
Brute force, and why it fails
For each node, compute both subtree heights from scratch: O(n²).
The key insight
The height function already visits every node with both children's heights, so the best bend can be recorded on the way.
Dry run
| best | 0 |
|---|
[1, 2, 3, 4, 5]. Leaves 4, 5 and 3 have height 1.
The plan
depth(n): if null: 0
l = depth(left); r = depth(right)
best = max(best, l + r)
return 1 + max(l, r)
Complexity
- Time
O(n)- Space
O(h)
One post-order pass.
Edge cases
- One node: 0.
- A chain of n nodes: n - 1.
- The longest path inside one subtree.
I've built my logic, show the code
Java
class Solution {
private int best = 0;
public int diameterOfBinaryTree(TreeNode root) {
best = 0;
depth(root);
return best;
}
private int depth(TreeNode n) { // returns the height; records the longest path through n
if (n == null) return 0;
int l = depth(n.left), r = depth(n.right);
best = Math.max(best, l + r); // edges down the left plus edges down the right
return 1 + Math.max(l, r);
}
}C++
class Solution {
public:
int best = 0;
int diameterOfBinaryTree(TreeNode* root) {
best = 0;
depth(root);
return best;
}
int depth(TreeNode* n) { // returns the height; records the longest path through n
if (n == NULL) return 0;
int l = depth(n->left), r = depth(n->right);
best = max(best, l + r); // edges down the left plus edges down the right
return 1 + max(l, r);
}
};Python
class Solution:
def diameterOfBinaryTree(self, root) -> int:
best = 0
def depth(n) -> int: # returns the height; records the longest path through n
nonlocal best
if not n:
return 0
l, r = depth(n.left), depth(n.right)
best = max(best, l + r) # edges down the left plus edges down the right
return 1 + max(l, r)
depth(root)
return bestCommon mistakes
- Counting nodes instead of edges.
- Only checking paths through the root.