Find the best path anywhere in a tree. Each node reports its best one-sided branch upward and checks the path that bends through it.
▼The problem
LeetCode 124 (Hard). A path in a binary tree is any sequence of nodes joined by edges, each node used at most once; it can start and end anywhere and doesn't have to pass through the root. Return the largest sum of node values over all non-empty paths.
Example: [-10, 9, 20, -4, null, 15, 7] → 42, the path 15 → 20 → 7, which skips the root.
def maxPathSum(root):
best = float('-inf')
def gain(node):
nonlocal best
if not node:
return 0
left = max(0, gain(node.left)) # drop < 0
right = max(0, gain(node.right))
best = max(best, node.val + left + right) # bend
return node.val + max(left, right) # one arm
gain(root)
return bestTRY IT ON LEETCODE ▶The solution
def maxPathSum(root):
best = float('-inf')
def gain(node):
nonlocal best
if not node:
return 0
left = max(0, gain(node.left)) # drop < 0
right = max(0, gain(node.right))
best = max(best, node.val + left + right) # bend
return node.val + max(left, right) # one arm
gain(root)
return bestTranscript
Binary Tree Maximum Path Sum. A path is a chain of connected nodes, each used at most once. It can start and end anywhere; it doesn't have to pass through the root. Find the largest path sum.
Here's our tree. Minus ten is the root. Nine is on the left, with minus four below it. Twenty is on the right, with fifteen and seven. The best path is fifteen, twenty, seven: forty-two. It skips the root.
The simple way tries every pair of endpoints and adds up the path between them. That's fifteen pairs here, and about n squared in a big tree. Too slow.
The key idea: every path bends at one highest node, and reaches down at most two arms. So ask each node: what's the best gain down just one arm? Work up from the leaves. If an arm's gain is negative, drop it and take zero.
In code, a helper returns a node's one-arm gain. It takes the left and right gains, floored at zero. It updates the best with the node plus both arms: the path that bends here. Then it returns the node plus the bigger arm, since a parent can extend only one side.
Let's run it. Minus four is a leaf: gain minus four, so the best is minus four for now. Nine drops that negative arm and takes zero: bend nine, best nine. Fifteen raises the best to fifteen. Seven gives seven. At twenty, bending gives fifteen plus twenty plus seven: forty-two, the new best. Twenty sends up twenty plus fifteen: thirty-five. At the root, bending gives minus ten plus nine plus thirty-five: only thirty-four. The best stays forty-two.
Each node is visited once, so the time is O of n. The space is the recursion stack, as deep as the tree is tall: O of h.
Gains flow up, the best bend wins. That's Binary Tree Maximum Path Sum.