Binary Tree Maximum Path Sum
Find the path with the largest total of its node values
DSA, Hard, 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. A path follows parent-child links, visits each node at most once, and has at least one node. It may start and end at any node and need not use the root. Return the largest sum of node values over all paths.
Examples
Constraints
- 1 <= number of nodes <= 30,000.
- Each value is a whole number between -3,000 and 3,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
Look at the highest node of the best path. What two parts does the path have below that node?
Hint 2 the approach
Each part is a path going straight down from a child. A part with a negative total should be left out. What must each child report?
Hint 3 the key step
For each node, find the best path that starts there and goes down one side. Add the node and both child sums, ignoring negatives. Keep the largest total.
Walkthrough
Full walkthrough brute force to best
Brute force
Try every pair of nodes as the two ends of a path, find the path between them and add its values. There are about n^2 / 2 pairs, and adding a path can take up to n steps. That is O(n^2) time or worse, far too slow for 30,000 nodes.
Best method
Every path has one highest node, where it bends or ends. Below that node the path takes a straight part down the left side and a straight part down the right side, or leaves one side out. So for each node, compute its downward gain: the best sum of a path that starts at the node and goes down one side only. It is the node value plus the larger child gain, and a child gain below 0 is replaced by 0, since leaving that side out is better. The best path with this node as its highest node is the node value plus the two non-negative child gains. Keep the largest such total. Process the nodes in reverse reading order so children come first. Start the best total from the root value, not 0, so an all-negative tree works.
Hand trace
Run on [-3, 4, 5, -1, 6, null, 2]. The tree: -3 has children 4 and 5. Node 4 has children -1 and 6. Node 5 has a right child 2. Reading order is -3, 4, 5, -1, 6, 2, so we go 2, 6, -1, 5, 4, -3. Node 2: gain 2, total 2. Node 6: gain 6, total 6. Node -1: gain -1, total -1. Node 5: right gain 2, so gain 7 and total 7. Node 4: left gain -1 becomes 0, right gain 6, so gain 10 and total 10. Node -3: left gain 10, right gain 7, so total -3 + 10 + 7 = 14 and the gain is 7. The largest total is 14.
Code
def max_path_sum(root):
order = [root]
for node in order:
order.extend(child for child in (node.left, node.right) if child)
gain, best = {}, root.val
for node in reversed(order):
left = max(0, gain.get(node.left, 0))
right = max(0, gain.get(node.right, 0))
gain[node] = node.val + max(left, right)
best = max(best, node.val + left + right)
return bestTime and memory
O(n) time, because each node is listed once and its gain is set once. O(n) memory for the order and the gains.
Common mistakes
- Starting the best total at 0. When every value is negative, the answer is the largest single value, as in example 3.
- Not cutting a negative gain to 0. A branch that lowers the sum should be left out.
- Passing a bent path up to the parent. A path that goes up through a node can use only one of its two sides, so the gain returned upward uses the larger child gain only.