Binary Tree Maximum Path Sum
Pattern: Path sums
A path bends at one node. For each node compute its best downward 'gain' (itself plus the better child gain, never below 0 from a child). The best path bending here is the value plus both child gains; the answer is the best of those.
The problem
A path is any sequence of nodes joined by edges, each used once, with at least one node. Return the largest sum of a
path. [-10, 9, 20, null, null, 15, 7] gives 42. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Where does the best path turn?
- What can a node pass up to its parent?
- When should a child's side be ignored?
Hints
Brute force, and why it fails
Try every pair of nodes as the ends: O(n²) or worse.
The key insight
Like the diameter, the post-order pass gives each node its children's best one-sided paths, so the best bend is found on the way.
Dry run
| best | 15 |
|---|
[-10, 9, 20, null, null, 15, 7]. Gains of the leaves: 9, 15, 7.
The plan
gain(n): if null: 0
l = max(0, gain(left)); r = max(0, gain(right))
best = max(best, n.val + l + r)
return n.val + max(l, r)
Complexity
- Time
O(n)- Space
O(h)
One post-order pass.
Edge cases
- All negative: the largest single value.
- One node.
- The best path inside one subtree.
I've built my logic, show the code
Java
class Solution {
private int best;
public int maxPathSum(TreeNode root) {
best = Integer.MIN_VALUE;
gain(root);
return best;
}
private int gain(TreeNode n) { // the best sum of a path going down from n (n included)
if (n == null) return 0;
int l = Math.max(0, gain(n.left)), r = Math.max(0, gain(n.right)); // a negative side is better left out
best = Math.max(best, n.val + l + r); // the best path that bends at n
return n.val + Math.max(l, r); // a path going up can use only one side
}
}C++
class Solution {
public:
int best;
int maxPathSum(TreeNode* root) {
best = INT_MIN;
gain(root);
return best;
}
int gain(TreeNode* n) { // the best sum of a path going down from n (n included)
if (n == NULL) return 0;
int l = max(0, gain(n->left)), r = max(0, gain(n->right)); // a negative side is better left out
best = max(best, n->val + l + r); // the best path that bends at n
return n->val + max(l, r); // a path going up can use only one side
}
};Python
class Solution:
def maxPathSum(self, root) -> int:
best = float("-inf")
def gain(n) -> int: # the best sum of a path going down from n (n included)
nonlocal best
if not n:
return 0
l, r = max(0, gain(n.left)), max(0, gain(n.right)) # a negative side is better left out
best = max(best, n.val + l + r) # the best path that bends at n
return n.val + max(l, r) # a path going up can use only one side
gain(root)
return bestCommon mistakes
- Starting
bestat 0, which fails when everything is negative. - Passing both sides up to the parent.