Binary Tree Maximum Path Sum (LeetCode 124): Solution and Explanation

Hard
Dynamic Programming
Tree
Depth First Search
Binary Tree

A path in a binary tree is any sequence of connected nodes where each node appears at most once, and it does not have to pass through the root. Given the root, return the largest possible sum of node values along any non-empty path. Values can be negative.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Brute force would consider every pair of nodes, find the path between them, and add up the values. That is at least quadratic and does a lot of repeated work. The better route is to ask what a path looks like from the point of view of its highest node.

Every path has exactly one topmost node. From there, the path can extend down into the left subtree, down into the right subtree, both, or neither. So if every node knew the best sum of a path that starts at its left child and goes straight down, and the same for its right child, it could compute the best path that peaks at itself as node.val + leftGain + rightGain. Taking the maximum of that over all nodes gives the answer.

There is one subtlety about what a node reports to its parent. A parent can only continue a path through one child, since a path cannot fork. So the value returned upward must be a single downward chain: node.val + max(leftGain, rightGain). The value used to update the global answer is the split path that uses both sides. Negative gains are clamped to zero, because if a subtree only drags the sum down, it is better not to extend into it at all.

Approach: Postorder DFS with gains and a global maximum

  1. Initialize res to [root.val] so a single-node path is always a valid baseline, even when every value is negative.
  2. Define dfs(node), which returns the best sum of a downward path starting at node. A None node returns 0.
  3. Recursively compute leftMax and rightMax, then clamp each to at least 0 so negative branches are dropped.
  4. Update res[0] with root.val + leftMax + rightMax, the best path that peaks at this node and may use both sides.
  5. Return root.val + max(leftMax, rightMax) to the parent, since a path continuing upward can only use one branch.
  6. Call dfs(root) and return res[0].

Step-by-step example

root = [-10,9,20,null,null,15,7]
  1. Start with res at -10. The leaf 9 has zero gains on both sides, so it updates res to 9 and returns 9.
  2. Leaf 15 updates res to 15 and returns 15. Leaf 7 leaves res at 15 and returns 7.
  3. At node 20, the gains are 15 and 7. The split path 15 + 20 + 7 = 42 updates res to 42, and the node returns 20 + 15 = 35.
  4. At the root -10, the gains are 9 and 35. The split path sums to 34, which does not beat 42.
  5. The answer is 42, the path 15 -> 20 -> 7, which does not include the root.

Code: Python, Java, C++

1class Solution:
2    def maxPathSum(self, root: Optional[TreeNode]) -> int:
3        res = [root.val]
4        
5        def dfs(root):
6            if not root:
7                return 0
8            
9            leftMax = dfs(root.left)
10            rightMax = dfs(root.right)
11            leftMax = max(leftMax, 0)
12            rightMax = max(rightMax, 0)
13            
14            res[0] = max(res[0], root.val + leftMax + rightMax)
15            
16            return root.val + max(leftMax, rightMax)
17            
18        dfs(root)
19        return res[0]

Time and space complexity

Time

O(n)

Each node is visited exactly once, and the work at each node is a few additions and comparisons.

Space

O(h)

Only the recursion stack is used, which grows to the height of the tree. That is O(log n) for balanced trees and O(n) for skewed ones.

Other approaches

Brute force from every node (time O(n²), space O(h))

For each node, compute the best downward path into each subtree with a separate DFS and combine them. It follows the same idea but recomputes subtree gains repeatedly, which is wasteful on deep trees.

Iterative postorder with a gain map (time O(n), space O(n))

Produce a postorder sequence with an explicit stack, then process nodes in that order while storing each node's gain in a hash map. It avoids recursion limits on very deep trees at the cost of extra memory.

Common mistakes

  • Returning the split value node.val + leftMax + rightMax to the parent. A path cannot fork, so only one branch can continue upward.
  • Initializing the answer to 0. If every node is negative, the correct answer is the largest single value, which is why res starts at root.val.
  • Forgetting to clamp negative gains to 0, which forces the path to include branches that only lower the sum.
  • Assuming the path must pass through the root or end at a leaf. It can start and end anywhere.

Frequently asked questions

Why does the DFS return a different value than it uses to update the answer?

The global answer can use both children because the current node may be the top of the path. The returned value is what a parent can extend, and a parent can only attach one downward chain, so it uses the larger of the two gains.

How does the solution handle all negative values?

Negative gains are clamped to zero, so each node considers itself alone as a path. Since the answer starts at the root's value and is compared at every node, it ends up as the largest single node value.

What is the time complexity of Binary Tree Maximum Path Sum?

It is O(n) time, because each node is processed once in a postorder traversal, and O(h) space for the recursion stack.