Binary Tree Maximum Path Sum

Hard

Topics
TreeDFSDynamic Programming

A path is any sequence of nodes connected by parent-child edges; it need not pass through the root. The path sum is the sum of the node values. Given the root, return the maximum path sum of any non-empty path.

Example 1

213
The shaded path sums to 6. Two things make this harder than it looks: the path can turn once at its highest node rather than running root-downward, and a negative subtree is better dropped than carried — hence clamping each child’s contribution at zero.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,3]
Output: 6

Example 2

9-1015207
Input:  root = [-10,9,20,null,null,15,7]
Output: 42

Constraints

  • 1 <= number of nodes <= 3*10^4
  • -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

At each node the best path that bends here is node.val + max(leftGain, 0) + max(rightGain, 0). But what you can hand to a parent is only a straight downward branch, so you return node.val + max(leftGain, rightGain, 0).

Approach

  1. DFS returning the best downward gain from each node (clamped at 0 so negative branches are dropped).
  2. At each node update a global best with the bent path through it.
  3. Return the straight branch gain to the parent.

Dry Run

tree = [-10, 9, 20, null, null, 15, 7]

`gain(node)` returns the best downward path STARTING at node, and separately
updates `best` with the path that turns at node. Negative gains are clamped to
0, which means "do not take that side at all".

node 9    l=0  r=0   through = 9              best 9     returns 9
node 15   l=0  r=0   through = 15             best 15    returns 15
node 7    l=0  r=0   through = 7              best 15    returns 7
node 20   l=15 r=7   through = 20+15+7 = 42   best 42    returns 20+15 = 35
node -10  l=9  r=35  through = -10+9+35 = 34  best 42    returns -10+35 = 25

answer 42   (the path 15 -> 20 -> 7)

The two different numbers at each node are the whole trick. `through` may use
both children, because a path is allowed to turn -- that is the answer
candidate. The RETURN value may use only one, because the parent needs a path
it can extend upward. Returning `through` instead would let a path fork twice,
which is not a path.

Note the root: 34 is worse than 42, so the best path does not contain the root
at all. Any solution that assumes the answer passes through the root gets this
wrong.

Complexity

  • Time — O(n): one post-order pass.
  • Space — O(h): recursion stack.

Common Pitfalls

  • Clamp negative child gains to 0, but still allow an all-negative tree to answer with its largest single node.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def maxPathSum(self, root):
        self.best=float('-inf')
        def gain(node):
            if not node: return 0
            l=max(gain(node.left),0); r=max(gain(node.right),0)
            self.best=max(self.best,node.val+l+r)
            return node.val+max(l,r)
        gain(root)
        return self.best
SensAI
Beta
Tap the mic to stop voice mode