Binary Tree Maximum Path Sum
Find the largest sum of node values along any path in a binary tree, which may start and end at any node.
A path in a binary tree is a chain of nodes where each node is joined to the next by a parent-child link, and no node is used twice. It can start and end at any node and does not have to pass through the root. Given the root of a binary tree, return the largest sum of node values on any path with at least one node.
Example 1
Output: 6
Explanation: the path 2 ā 1 ā 3 adds up to 6.
Example 2
Output: 42
Explanation: the path 15 ā 20 ā 7 adds up to 42. Adding -10 would only lower the sum.
The Idea
Think of the tree as towns joined by roads, where each town is worth some points, maybe negative. You may travel along the roads, never visiting a town twice, and you collect the points of every town you pass. Where should the trip start and end to collect the most?
The input lists the tree level by level, with null
There are many possible trips, so how can we look at all of them without listing each one? Follow any trip and notice its highest node, the one closest to the root. From there the trip goes down on the left, down on the right, both, or neither, and it never turns back up. So every path bends at exactly one node.
That splits the question into one question per node: what is the best path that bends here? It is the node's own value, plus the best way down into the left branch, plus the best way down into the right branch. We will call the best sum of a path that starts at a node and only goes down from it the node's gain.
Look at the picture above. The leaves 9, 15 and 7 have nothing below them, so each gain is just the value. Node 20 can go down to 15 or to 7, and 15 is better, so its gain is 20 + 15 = 35. In the box labelled "path bending at 20", both branches join: 15 + 20 + 7 = 42.
The box labelled "path bending at -10" joins the gain 9 on the left and the gain 35 on the right: 9 + (-10) + 35 = 34. That is less than 42, so the answer stays 42. Notice that a gain only ever goes down one side. A path coming up from a parent cannot go down both branches of a child, or it would bend twice.
Solution Approach
Trying every path works but is slow. The bend idea replaces it, and turning that idea into code means settling four things: how to compute every gain in one walk, what to do with negative branches, where to keep the best bend, and what the best starts at.
Trying every path
Why not list every path? Any two nodes, or one node on its own, give exactly one path, so a tree of n nodes has about n²/2 paths. Adding up each one takes up to n more steps. For 10,000 nodes that is hundreds of billions of steps.
Computing the gains from the bottom up
How do we get every gain without repeating work? A node's gain needs the gains of its two children, so the children must be done first. A recursive method gain(node)
Leaving out negative branches
What if a branch only brings negative points? Then the path is better off not going there. In the tree [1, -2, 3]Math.max(0, gain(child))
Keeping the best bend
Where does the answer live, if gainbest
Starting value of the best
What should best[-3]Integer.MIN_VALUEint
Java Solution
The method maxPathSum
- First, set the field
tobest , then callInteger.MIN_VALUE , which visits the whole tree.gain(root) - In
, again node returns 0, because a missing child adds nothing.null - Otherwise, call
on the left child and keep the result ingain , using 0 if it is negative. Do the same for the right child, intoleft .right - Work out the path that bends at this node,
, and keep it innode.val + left + right if it is larger.best - Return
plus the larger ofnode.val andleft : the node's gain, which its parent can extend.right - When
is done, every node has been a bend once, sogain(root) returnsmaxPathSum .best
The small class TreeNodebuildmain
public class BinaryTreeMaximumPathSum {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
private int best;
public int maxPathSum(TreeNode root) {
best = Integer.MIN_VALUE;
gain(root);
return best;
}
// Best sum of a path that starts at node and goes down one side.
private int gain(TreeNode node) {
if (node == null) {
return 0;
}
int left = Math.max(0, gain(node.left)); // a negative branch is left out
int right = Math.max(0, gain(node.right));
best = Math.max(best, node.val + left + right); // path bending at this node
return node.val + Math.max(left, right); // the parent can use one side only
}
// Builds a tree from level order, where null means no node.
static TreeNode build(Integer... values) {
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (i < values.length) {
TreeNode node = queue.remove();
if (values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
static void run(Integer... values) {
int sum = new BinaryTreeMaximumPathSum().maxPathSum(build(values));
System.out.println(java.util.Arrays.toString(values) + " -> " + sum);
}
public static void main(String[] args) {
run(1, 2, 3);
run(-10, 9, 20, null, null, 15, 7);
run(1, -2, 3);
run(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1);
run(-3);
run(-2, -1);
}
}
Running it prints:
[1, 2, 3] -> 6
[-10, 9, 20, null, null, 15, 7] -> 42
[1, -2, 3] -> 4
[5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1] -> 48
[-3] -> -3
[-2, -1] -> -1
The first two lines give 6 and 42, as in the examples. The third line, 4 for [1, -2, 3]
The last two lines are the trees with no positive values. [-3][-2, -1]best
Complexity
All the work happens in one walk of the tree by gain
- Time: O(n), for a tree of n nodes.
runs once on every node and once on every missing child, and besides its two recursive calls, each call does only a few comparisons and additions: two kept gains, one bend, one return value.gain - Space: O(h), where h is the number of levels in the tree. The recursion keeps one unfinished call per level on the way down, and only
is stored besides. A tree that is a single chain of n nodes has h equal to n.best
Using 0 in place of a branch that only loses points is the same move as dropping a negative running sum in