Binary Tree Maximum Path Sum
Find the largest sum of any path in the tree, letting every node be the place where the path bends.
The problem
You get the root of a non-empty binary tree whose values can be negative. A path is a chain of nodes where each neighboring pair is joined by an edge and no node is used twice; it can start and end anywhere and does not need to pass through the root. Return the largest sum of values over all paths with at least one node.
Input root = [4, -7, 6, null, null, 2, 5]
Output 15
The path 5, 6, 4 adds up to 15. Going on to -7 only lowers the sum, and the path can't branch to take 2 as well.
Input root = [-3, -8, -2]
Output -2
Every value is negative, so the best path is the single node -2.
How to spot the pattern
- The path can start and end at any node, so every node is a possible turning point.
- Negative values mean that leaving a branch out is sometimes the best choice.
The idea
Every path has one highest node where it bends, and from there it goes down at most one branch on each side. The best path bending at a node is its value plus the best downward gain from each child, with a negative gain replaced by 0. The parent can only continue down one side, so the DFS returns the node's value plus the larger gain, while a running best keeps track of the bent paths.
Brute force: Try every pair of nodes as the two ends of a path and add up the values between them, which takes O(n^2) time or more.
Step by step
- 1Write
gain(node): the best sum of a path that starts atnodeand goes down one side, with 0 for null. - 2Get the gains of both children, replacing a negative gain with 0.
- 3Update the best answer with
node.val + left + right, the best path that bends at this node. - 4Return
node.val + max(left, right)so the parent can extend one side. - 5Start the best at the root's value, call
gain(root)and return the best.
See the pattern move
The tree dfs and bst pattern on a small example. Step through it, or press play.
Code
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
best = root.val
def gain(node: Optional[TreeNode]) -> int:
# Best sum of a path that starts at node and goes down one side.
nonlocal best
if node is None:
return 0
left = max(gain(node.left), 0) # a negative branch is better left out
right = max(gain(node.right), 0)
best = max(best, node.val + left + right) # the best path that bends at node
return node.val + max(left, right)
gain(root)
return bestComplexity
Time
O(n)
Space
O(h)
One post-order pass handles each node once; the recursion stack is as deep as the tree's height h.
Watch out for
- Returning
node.val + left + rightto the parent: a path that bends at this node can't also go up to its parent. - Starting the best at 0, which gives the wrong answer when every value is negative.
- Keeping negative gains, so a bad branch drags the sum down instead of being dropped.
Follow-up questions
How would you return the path itself, not just its sum?
Remember which child gave each node its larger gain, and the node where the best path bends. From that node, follow the remembered choices down both sides.
What if the path had to start at the root and end at a leaf?
Then nothing bends. Compute bottom-up node.val plus the better answer of its existing children (a leaf returns just its value), and keep negative branches, because the path must reach a leaf.
In Hinglish
Har node par do sawaal: yahan mudne wala path kitna bada hai (node + left + right), aur parent ko kaunsi ek side doge (node + badi side). Negative branch ho toh use 0 maan lo.