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
Input: root = [1, 2, 3]
Output: 6
Explanation: the path 2 → 1 → 3 adds up to 6.
Example 2
Input: root = [-10, 9, 20, null, null, 15, 7]
Output: 42
Explanation: the path 15 → 20 → 7 adds up to 42. Adding -10 would only lower the sum.
Solution

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 for a missing child. In Example 2 the root is -10, its children are 9 and 20, and 20 has the children 15 and 7. A trip from 9 up to -10 and down through 20 to 15 collects 9 - 10 + 20 + 15 = 34. The trip 15, 20, 7 skips -10 and collects 42, which is the best.

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.

The tree of Example 2 with the gain of each node: 9, 15, 7, 35 for node 20 and 25 for node -10. The path bending at 20 is 15 + 20 + 7 = 42, the path bending at -10 is 9 + (-10) + 35 = 34, and the best of all bends is 42.

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), one that calls itself on the left child and the right child before using their answers, does exactly that. A missing child has nothing to offer, so it gives 0.

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], the branch below 1 on the left is worth -2, so the best path skips it and takes 1 + 3 = 4. Using 0 in place of any negative gain covers this: Math.max(0, gain(child)).

Keeping the best bend

Where does the answer live, if gain returns only one side? Each call also works out the path that bends at its node, value plus both kept gains, and compares it with a field best. The call then returns the one-sided gain to its parent. The bend is never returned, because a parent can extend only one side.

Starting value of the best

What should best start at? A path needs at least one node, so in the tree [-3] the answer is -3. Starting at 0 would report a sum that no path has. Starting at Integer.MIN_VALUE, the smallest int, lets the first real bend replace it.

Java Solution

The method maxPathSum works in these steps:

  1. First, set the field best to Integer.MIN_VALUE, then call gain(root), which visits the whole tree.
  2. In gain, a null node returns 0, because a missing child adds nothing.
  3. Otherwise, call gain on the left child and keep the result in left, using 0 if it is negative. Do the same for the right child, into right.
  4. Work out the path that bends at this node, node.val + left + right, and keep it in best if it is larger.
  5. Return node.val plus the larger of left and right: the node's gain, which its parent can extend.
  6. When gain(root) is done, every node has been a bend once, so maxPathSum returns best.

The small class TreeNode holds a value and two children, and build makes a tree from the level-by-level list. The main method runs both examples, the tree with a negative branch, a deeper tree where the best path bends at the root, a single negative node, and a tree of only negative values.

Java
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:

Output
[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], shows the -2 branch left out. The fourth tree is larger, and its 48 comes from the path 7 → 11 → 4 → 5 → 8 → 13, which bends at the root 5 and runs down to a leaf on each side.

The last two lines are the trees with no positive values. [-3] gives -3, the only path there is. For [-2, -1] the best path is the single node -1, because adding -2 only lowers it. Change the start value of best to 0 and run it again: those two lines then print 0, a sum that no path in either tree has.

Complexity

All the work happens in one walk of the tree by gain.

  • Time: O(n), for a tree of n nodes. gain 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.
  • 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 best is stored besides. A tree that is a single chain of n nodes has h equal to n.

Using 0 in place of a branch that only loses points is the same move as dropping a negative running sum in Kadane's algorithm, here applied on a tree.