Binary Tree Maximum Path Sum
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given the root of a binary tree, return the maximum path sum of any path in it.
Understand the problem
- A path is a chain of nodes where each node is connected to the next by a parent-child link, and no node is used twice. Think of tracing a line along the branches without lifting your pen or retracing.
- A path can go up and then down: for example, from a left child, up to its parent, and down to the right child.
- A path doesn't have to include the root, and it can be a single node.
- The path sum is the total of the values on it. Values can be negative.
Example 1
Input: root = [1, 2, 3]
Output: 6
1
/ \
2 3The path 2 → 1 → 3 sums to 6.
Example 2
Input: root = [-10, 9, 20, null, null, 15, 7]
Output: 42
-10
/ \
9 20
/ \
15 7The best path is 15 → 20 → 7 = 42. Going up through -10 would only lower the sum.
Example 3
Input: root = [-3]
Output: -3A path has at least one node, so the answer is -3, even though it's negative.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.
Constraints
1 <= number of nodes <= 3 * 10^4-1000 <= Node.val <= 1000
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
For each node, compute the best downward path starting there; use both sides to update the best "path topped at this node", but pass only the better side up to the parent.
The naive approach (and why it's slow)
Try every pair of nodes as the two ends of a path and add up the values between them. There are about n² pairs, and each path can be long: far too slow for 30,000 nodes.
The key insight
Every path has one highest node (its "top"). From the top, the path goes down into the left subtree, down into the right subtree, or both:
(best path going down on the left) + top.val + (best path going down on the right)If a side would add a negative sum, it only hurts, so we use 0 for it (skip that side).
So define gain(node) = the best sum of a path that starts at node and goes down one side only. At each node:
left = max(gain(node.left), 0)andright = max(gain(node.right), 0).- Record: the best path with this node as its top is
node.val + left + right. Compare it with the best found so far. - Return to the parent:
node.val + max(left, right). A path that continues up to the parent can only use one side, otherwise it would fork like aY, and a path can't do that.
Keeping "what I record" separate from "what I return" is the whole trick.
Step by step
root = [-10, 9, 20, null, null, 15, 7]. The recursion finishes the bottom nodes first:
| Node | left | right | Path topped here (record) | Best so far | Returns val + max(left, right) |
|---|---|---|---|---|---|
9 | 0 | 0 | 9 | 9 | 9 |
15 | 0 | 0 | 15 | 15 | 15 |
7 | 0 | 0 | 7 | 15 | 7 |
20 | 15 | 7 | 20 + 15 + 7 = 42 | 42 | 20 + 15 = 35 |
-10 | 9 | 35 | -10 + 9 + 35 = 34 | 42 | -10 + 35 = 25 |
The answer is 42: the path 15 → 20 → 7.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). One visit per node.
- Memory: O(h) for the recursion, where
his the height.
Common mistakes
- Returning
node.val + left + rightto the parent. That path uses both sides and goes up, which is a fork. Return only one side. - Starting the best at
0. If all values are negative (like[-3]), the answer is negative. Start at-Infinity. - Not clamping negative gains to
0. A side with a negative sum should be skipped, not added.
Going deeper
This "return one thing, record another" pattern appears in other tree problems. The closest is Diameter of Binary Tree (the longest path between any two nodes): the same structure, counting edges instead of adding values.
Reference solution
/**
* @param {TreeNode} root
* @return {number}
*/
export default function maxPathSum(root) {
// Best path sum found anywhere. Start at -Infinity: all values might be negative.
let best = -Infinity
// Returns the best sum of a path that STARTS at node and goes DOWN one side only.
function gain(node) {
if (!node) return 0
// Best way down on each side. A negative sum only hurts, so skip it (use 0).
const left = Math.max(gain(node.left), 0)
const right = Math.max(gain(node.right), 0)
// RECORD: the best path whose highest node is this one can use both sides.
best = Math.max(best, node.val + left + right)
// RETURN: a path going up to the parent can only continue down ONE side.
return node.val + Math.max(left, right)
}
gain(root)
return best
}export default function maxPathSum(root: TreeNode | null): number {
// Best path sum found anywhere. Start at -Infinity: all values might be negative.
let best = -Infinity
// Returns the best sum of a path that STARTS at node and goes DOWN one side only.
function gain(node: TreeNode | null): number {
if (!node) return 0
// Best way down on each side. A negative sum only hurts, so skip it (use 0).
const left = Math.max(gain(node.left), 0)
const right = Math.max(gain(node.right), 0)
// RECORD: the best path whose highest node is this one can use both sides.
best = Math.max(best, node.val + left + right)
// RETURN: a path going up to the parent can only continue down ONE side.
return node.val + Math.max(left, right)
}
gain(root)
return best
}def max_path_sum(root: TreeNode | None) -> int:
# Best path sum found anywhere. Start at -inf: all values might be negative.
best = float("-inf")
# Returns the best sum of a path that STARTS at node and goes DOWN one side only.
def gain(node: TreeNode | None) -> int:
nonlocal best
if node is None:
return 0
# Best way down on each side. A negative sum only hurts, so skip it (use 0).
left = max(gain(node.left), 0)
right = max(gain(node.right), 0)
# RECORD: the best path whose highest node is this one can use both sides.
best = max(best, node.val + left + right)
# RETURN: a path going up to the parent can only continue down ONE side.
return node.val + max(left, right)
gain(root)
return best