Binary Tree Maximum Path Sum

hard

Given the root of a binary tree, return the maximum path sum of any non-empty path.

A path is any sequence of nodes connected by edges, where each node appears at most once; it need not pass through the root. The path sum is the sum of the nodes' values. Node values may be negative.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

For each node, the best path bending at it is node.val + best-left-gain + best-right-gain.
Clamp a negative child gain to 0 — an unhelpful branch should simply be dropped.
Return node.val + max(leftGain, rightGain) upward, but record node.val + leftGain + rightGain globally.

Common doubts

A branch with negative total only reduces the path sum, so it's better to stop and not include it — contributing 0.
The path is non-empty and all values can be negative, so the best path might be a single negative node; 0 would be wrong.
Same return-one-record-both structure, but you sum node values (with a 0-clamp) instead of counting edges.

Interview follow-ups

Remember which node achieved the maximum and its two chosen branches, then walk down both sides from it.
You'd only evaluate the bending path at the root: root.val + max(0, gain(left)) + max(0, gain(right)).

Fun facts

  • Maximum path sum and tree diameter are the same algorithm with a different quantity combined at each node.
  • The 0-clamp is exactly Kadane's 'reset when the running sum goes negative', lifted onto a tree.

Asked at

AmazonFacebookMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 2, 3]
Output: 6
The path 2 -> 1 -> 3 sums to 6.
Example 2
Input: root = [-10, 9, 20, null, null, 15, 7]
Output: 42
The path 15 -> 20 -> 7 sums to 42; going up to -10 would only reduce it.
Constraints

- The number of nodes is in the range [1, 3 * 10^4] - -1000 <= Node.val <= 1000

Solve this problem →