Binary Tree Maximum Path Sum (LeetCode 124): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Initialize
resto[root.val]so a single-node path is always a valid baseline, even when every value is negative. - Define
dfs(node), which returns the best sum of a downward path starting atnode. A None node returns 0. - Recursively compute
leftMaxandrightMax, then clamp each to at least 0 so negative branches are dropped. - Update
res[0]withroot.val + leftMax + rightMax, the best path that peaks at this node and may use both sides. - Return
root.val + max(leftMax, rightMax)to the parent, since a path continuing upward can only use one branch. - Call
dfs(root)and returnres[0].
Step-by-step example
root = [-10,9,20,null,null,15,7]
- Start with
resat -10. The leaf 9 has zero gains on both sides, so it updatesresto 9 and returns 9. - Leaf 15 updates
resto 15 and returns 15. Leaf 7 leavesresat 15 and returns 7. - At node 20, the gains are 15 and 7. The split path 15 + 20 + 7 = 42 updates
resto 42, and the node returns 20 + 15 = 35. - At the root -10, the gains are 9 and 35. The split path sums to 34, which does not beat 42.
- 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]1class Solution {
2 int res;
3 public int maxPathSum(TreeNode root) {
4 res = Integer.MIN_VALUE;
5 dfs(root);
6 return res;
7 }
8
9 public int dfs(TreeNode root) {
10 if (root == null) return 0;
11
12 int leftMax = Math.max(dfs(root.left), 0);
13 int rightMax = Math.max(dfs(root.right), 0);
14
15 res = Math.max(res, root.val + leftMax + rightMax);
16
17 return root.val + Math.max(leftMax, rightMax);
18 }
19}1class Solution {
2 int res = INT_MIN;
3public:
4 int maxPathSum(TreeNode* root) {
5 dfs(root);
6 return res;
7 }
8
9 int dfs(TreeNode* root) {
10 if (!root) return 0;
11
12 int leftMax = max(dfs(root->left), 0);
13 int rightMax = max(dfs(root->right), 0);
14
15 res = max(res, root->val + leftMax + rightMax);
16
17 return root->val + max(leftMax, rightMax);
18 }
19};Time and space complexity
O(n)
Each node is visited exactly once, and the work at each node is a few additions and comparisons.
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 + rightMaxto 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
resstarts atroot.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.