Binary Tree Maximum Path Sum
Problem
A path in a binary tree is a sequence of nodes in which each consecutive pair is connected by an edge and no node appears twice. A path can start and end at any nodes and does not have to pass through the root, but it must contain at least one node. The sum of a path is the sum of its nodes' values. Given the root, return the maximum path sum over all paths in the tree.
- The tree has between 1 and 60,000 nodes.
- Node values are integers between -5,000 and 5,000; an all-negative tree is a valid input.
Examples
root = [4, 7, 2]→13. The path7 → 4 → 2uses all three nodes.root = [-8, 6, 15, None, None, 11, 9]→35. The path11 → 15 → 9avoids the negative root entirely.root = [-6]→-6. The path must contain at least one node, so an all-negative tree still has an answer.root = [3, -2]→3. Including the-2would only lower the sum.
Hints
- Every path has a unique topmost node where it bends. Describe the best path through a given node in terms of its two subtrees.
- A subtree can contribute to a path that continues upward only through a single downward branch, and it should contribute nothing at all if its best branch is negative.
- Post-order DFS returning the best single-branch gain,
max(0, node.val + max(gain_left, gain_right)), while recordingnode.val + gain_left + gain_rightas a candidate answer.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.