Skip to content
Problem 124 · LeetCode 124(opens in a new tab)

Binary Tree Maximum Path Sum

HardDepth-first search

You get the root of a binary tree whose nodes hold whole numbers, some of them negative. A path is a chain of nodes where each one is joined to the next by an edge, and no node is used twice. It can start and end anywhere, and it does not have to go through the root.

A path must contain at least one node. Its sum is the total of the values on it. Return the largest sum any path can have.

Example 1

Input:  root = [-4, 8, 5, null, null, 3, -6]
Output: 12
Why:    8 → -4 → 5 → 3 adds up to 12
2 more examples and the constraints

Example 2

Input:  root = [5, -8, null, 7, 4]
Output: 7
Why:    the node 7 alone beats every longer path

Example 3

Input:  root = [-5, -2, -9]
Output: -2
Why:    every value is negative, so take the largest one

Constraints

  • 1 ≤ number of nodes ≤ 30,000
  • −1,000 ≤ Node.val ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every bendO(n²)
  2. One post-order DFSO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 30,000-node chainVerdict
Try every bendO(n²)
Correct; redoes each subtree
One post-order DFSO(n)
Best; one visit per node

n = number of nodes, h = height of the tree.

Edge cases to test

  • All values negative. [-5, -2, -9] must give −2, the single best node, not 0.
  • One node. The answer is that node, even when it is −1,000.
  • A single node beats the rest. In Example 2, adding −8 to reach more nodes only lowers the sum.
  • Best path deep down. It can sit entirely inside one subtree and never touch the root.
  • A long chain. The recursion is n deep, so the stack must allow it.

Common mistakes

  • Returning node + left + right to the parent; a path cannot fork, so only one side may continue upward.
  • Starting best at 0, which breaks trees where every value is negative.
  • Forgetting to clamp a negative child gain to 0, so a bad side drags the sum down.

How to talk through it

  1. 1Clarify. Can values be negative? Must the path go through the root? Can a path be a single node?
  2. 2Find the shape of a path. Every path has a highest node; there it is node + best left side + best right side.
  3. 3Give the simple version. Compute the downward paths again at every node; say why that is O(n²) on a chain.
  4. 4Merge the two jobs. One post-order DFS returns the one-sided gain and updates best with the two-sided bend.
  5. 5Test out loud. Run the all-negative tree and a single node before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?