Diameter of Binary Tree
Find the longest path between any two nodes
DSA, Easy, Trees
Which structure or algorithm, and what does it cost.
You get a binary tree tree. Your code may take the root node or the list. Each node has val, left and right, null when missing. Either is fine; no conversion is needed. The examples use a level-order list. It holds values row by row, left to right. Null marks a missing child. A missing node has no entries below it. An empty list is an empty tree. A path moves along parent-child links and never visits a node twice. It may start and end at any nodes and may skip the root. Return the number of edges on the longest path. A tree with 0 or 1 nodes gives 0.
Examples
Constraints
- 0 <= number of nodes <= 30,000.
- Each value is a whole number between -5,000 and 5,000.
- The tree can be one long chain.
Your answer must contain
- The simple method and why it is slow; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Draw the longest path in a tree. At which node does it turn from going up to going down?
Hint 2 the approach
At that top node the path goes down one side and then down the other. What must you know about each side? Any node could be the top.
Hint 3 the key step
Compute heights from the leaves upward. At each node, the left height plus the right height is a candidate. Keep the largest candidate.
Walkthrough
Full walkthrough brute force to best
Brute force
For every node, measure the height of its left subtree and of its right subtree by walking down each one, and add them. Each measurement walks a whole subtree. On a chain of n nodes the walks cost n, n - 1, n - 2 and so on, which is O(n^2) time.
Best method
The longest path has a highest node, where it turns from going down one side to going down the other. At that node the path length is the height of the left side plus the height of the right side. So try every node as the top. Heights are needed again and again, so compute each one once, from the leaves upward: a node is 1 higher than its taller child. Read the nodes in reverse reading order, so children come before their parent. Each node gives the candidate left + right, and the answer is the largest candidate. Each node is handled once, so the work is linear.
Hand trace
Run on [3, 9, null, 4, 7, 5, null, null, 8]. The tree: 3 has left child 9. Node 9 has children 4 and 7. Node 4 has left child 5. Node 7 has right child 8. Reading order is 3, 9, 4, 7, 5, 8, so we go 8, 5, 7, 4, 9, 3. Node 8: heights 0 and 0, its height is 1, candidate 0. Node 5: height 1, candidate 0. Node 7: left 0, right 1, height 2, candidate 1. Node 4: left 1, right 0, height 2, candidate 1. Node 9: left 2, right 2, height 3, candidate 4. Node 3: left 3, right 0, height 4, candidate 3. The largest candidate is 4.
Code
def diameter(root):
order = [root] if root else []
for node in order:
order.extend(child for child in (node.left, node.right) if child)
height, best = {}, 0
for node in reversed(order):
left, right = height.get(node.left, 0), height.get(node.right, 0)
height[node] = 1 + max(left, right)
best = max(best, left + right)
return bestTime and memory
O(n) time, because each node is placed in the order once and its height is set once. O(n) memory for the order and the heights.
Common mistakes
- Measuring only the path through the root. The longest path can sit entirely inside one side, as in example 1, where the best path through the root has only 3 edges.
- Counting nodes instead of edges. The answer is the node count minus 1.
- Returning the height of the tree. The height follows one path from the root, but the longest path can bend lower down.