15% off all plans & roadmaps Use code
See plansBinary Tree Maximum Path Sum
- LeetCode 124
- Hard
- Tree Traversal Patterns (DFS & BFS)
- Recursive Postorder Traversal
Updated
TL;DR: Find the largest sum over any path in a binary tree, where the path may bend once at its highest node. Run one postorder DFS that returns the best single-branch gain upward and records the best bent path at each node.
Problem
A path in a binary tree is a sequence of nodes in which every two neighbouring nodes share an edge. Each node may appear in the sequence at most once. The path does not have to pass through the root.
The path sum is the sum of the values of the nodes on the path.
Given the root of a binary tree, return the maximum path sum over all non-empty paths.
Example 1
Input: root = [1,2,3] Output: 6 Explanation: The best path is 2 -> 1 -> 3, with sum 2 + 1 + 3 = 6.
Example 2
Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The best path is 15 -> 20 -> 7, with sum 15 + 20 + 7 = 42.
Constraints
- The number of nodes in the tree is in the range
[1, 3 * 10^4]. -1000 <= Node.val <= 1000
Constraints that matter
- Up to 3 * 10^4 nodes means an O(n^2) solution does about 4.5 * 10^8 steps on a chain-shaped tree. That is too slow, so you need one linear pass.
- Values can be negative, so the answer can be negative and you cannot start your best-so-far at 0. A tree with the single node -3 must return -3.
- The path must be non-empty. You may never answer with an empty path of sum 0.
- The tree can be a chain 3 * 10^4 nodes deep. Recursion depth matters in languages with small default stacks, such as Python and JavaScript.
- Sums reach at most 3 * 10^4 * 1000 = 3 * 10^7, which fits in a 32-bit int, so overflow is not a concern.
Hints
Hint 1
This is a recursive postorder traversal problem.
Hint 2
Make every node the highest point of a candidate path.
Solution
Intuition
This is a recursive postorder traversal problem. A node's best answer depends on what its two children can offer, so you must finish the children before you finish the node. That is the signal for postorder: left, right, then process the node.
Picture a company org chart where each manager reports one number upward: the best single chain of people reporting through them. Each manager also checks whether their own team plus both sub-teams beats the record on the wall, which is the global best.
Every path in a tree has exactly one highest node, the one closest to the root. The path goes down into at most two child subtrees from that node, one on each side. So the answer is the best value of node.val + (best left arm) + (best right arm) taken over all nodes.
An arm is a path that starts at a child and only goes downward. It never splits. When a node reports to its parent, it can offer only one arm, because a path through the parent that branches into two children below would visit the node twice or form a Y shape.
So each node does two jobs. It uses both arms to score a bent path for the global answer, and it returns one arm to its parent.
Negative arms hurt, so you drop them. If a child's best arm is negative, you stop the path at the current node instead. That is why each arm is clamped at 0. The clamp applies only to arms, never to the node's own value, so the answer can still be negative.
Worked example
Input: root = [-10, 9, 20, null, null, 15, 7] Output: 42 Explanation: The tree has -10 at the root, a leaf 9 on the left, and 20 on the right with leaf children 15 and 7. The path 15 -> 20 -> 7 bends at 20 and sums to 42. Any path that uses the root must pay the -10 penalty, and the best of those is 9 + (-10) + 20 + 15 = 34, which is smaller.
Approach 1: Brute force: treat every node as the top
Make every node the highest point of a candidate path. For that node, compute the best downward arm into the left subtree and into the right subtree, add the node's value, and keep the maximum over all nodes.
The arm helper down(node) returns the best path that starts at node and walks down one branch. It is node.val + max(0, down(left), down(right)), with down(null) = 0. The helper walks a whole subtree every time you call it.
Steps
- Keep a variable
best, starting at the smallest possible integer. - Visit every node with any traversal. Call the visited node
u. - Compute
left = max(0, down(u.left))andright = max(0, down(u.right)). - Compute the bent path sum
u.val + left + rightand updatebest. - Define
down(n)as 0 for null, otherwisen.val + max(0, down(n.left), down(n.right)). - Return
bestafter every node has been visited.
Dry run
On [-10, 9, 20, null, null, 15, 7]:
- Node -10:
down(9) = 9,down(20) = 20 + max(0, 15, 7) = 35. Bent sum is-10 + 9 + 35 = 34. - Node 9: both arms are 0. Bent sum is 9.
- Node 20: arms 15 and 7. Bent sum is
20 + 15 + 7 = 42. - Node 15: bent sum 15. Node 7: bent sum 7.
The maximum of 34, 9, 42, 15, 7 is 42, which matches the expected output. Note that down(20) was computed again when 20 was visited itself, and 15 and 7 were walked a third time. That repeated work is the cost.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(h) |
Let n be the number of nodes and h the tree height. The outer traversal visits n nodes, and each visit calls down on two subtrees, which can touch every node below. In a chain of n nodes the calls cost n-1, n-2, ... , so the total is about n^2 / 2 steps. Space is the recursion depth of down, which is at most h, and h = n for a chain.
PythonTested in our runner
import sys
from typing import List, Optional
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
sys.setrecursionlimit(1 << 17)
def down(node):
# best path that starts at node and walks down one branch
if not node:
return 0
return node.val + max(0, down(node.left), down(node.right))
best = float('-inf')
stack = [root]
while stack:
node = stack.pop()
left = max(0, down(node.left))
right = max(0, down(node.right))
best = max(best, node.val + left + right)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return bestJavaTested in our runner
import java.util.*;
class Solution {
// best path that starts at n and walks down one branch
private int down(TreeNode n) {
if (n == null) return 0;
return n.val + Math.max(0, Math.max(down(n.left), down(n.right)));
}
public int maxPathSum(TreeNode root) {
int best = Integer.MIN_VALUE;
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode n = stack.pop();
int l = Math.max(0, down(n.left));
int r = Math.max(0, down(n.right));
best = Math.max(best, n.val + l + r);
if (n.left != null) stack.push(n.left);
if (n.right != null) stack.push(n.right);
}
return best;
}
}C++Tested in our runner
#include <algorithm>
#include <climits>
class Solution {
int best;
// best path that starts at n and walks down one branch
int down(TreeNode* n) {
if (!n) return 0;
return n->val + std::max(0, std::max(down(n->left), down(n->right)));
}
void visit(TreeNode* n) {
if (!n) return;
int l = std::max(0, down(n->left));
int r = std::max(0, down(n->right));
best = std::max(best, n->val + l + r);
visit(n->left);
visit(n->right);
}
public:
int maxPathSum(TreeNode* root) {
best = INT_MIN;
visit(root);
return best;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
// best path that starts at n and walks down one branch
const down = (n) => {
if (!n) return 0;
return n.val + Math.max(0, down(n.left), down(n.right));
};
let best = -Infinity;
const stack = [root];
while (stack.length > 0) {
const n = stack.pop();
const l = Math.max(0, down(n.left));
const r = Math.max(0, down(n.right));
best = Math.max(best, n.val + l + r);
if (n.left) stack.push(n.left);
if (n.right) stack.push(n.right);
}
return best;
};GoTested in our runner
func maxPathSum(root *TreeNode) int {
maxInt := func(a, b int) int {
if a > b {
return a
}
return b
}
// best path that starts at n and walks down one branch
var down func(n *TreeNode) int
down = func(n *TreeNode) int {
if n == nil {
return 0
}
return n.Val + maxInt(0, maxInt(down(n.Left), down(n.Right)))
}
best := root.Val
stack := []*TreeNode{root}
for len(stack) > 0 {
n := stack[len(stack)-1]
stack = stack[:len(stack)-1]
l := maxInt(0, down(n.Left))
r := maxInt(0, down(n.Right))
best = maxInt(best, n.Val+l+r)
if n.Left != nil {
stack = append(stack, n.Left)
}
if n.Right != nil {
stack = append(stack, n.Right)
}
}
return best
}C#Tested in our runner
public class Solution {
private int best;
// best path that starts at n and walks down one branch
private int Down(TreeNode n) {
if (n == null) return 0;
return n.val + Math.Max(0, Math.Max(Down(n.left), Down(n.right)));
}
private void Visit(TreeNode n) {
if (n == null) return;
int l = Math.Max(0, Down(n.left));
int r = Math.Max(0, Down(n.right));
best = Math.Max(best, n.val + l + r);
Visit(n.left);
Visit(n.right);
}
public int maxPathSum(TreeNode root) {
best = int.MinValue;
Visit(root);
return best;
}
}
Solution pattern
Recursive Postorder Traversal
Approach 2: One-pass postorder DFSOptimalRecursive Postorder Traversal
What's slow: the brute force recomputes the downward arm of the same node many times. The arm of node 15 is computed when visiting 20, again when visiting -10 through 20, and again when 15 itself is visited. Each arm depends only on the node's own subtree, so it never changes.
The insight that fixes it: compute each arm once, bottom-up, and use it twice on the spot. A postorder DFS returns the clamped arm max(0, node.val + max(left, right)) to the parent. In the same call, the node scores its bent path node.val + left + right against a global best. Every node is processed exactly once, and the arms of its children are already available.
Steps
- Set
bestto the smallest possible integer. A global or field works. - Define
gain(node). For null, return 0. - Compute
left = gain(node.left)andright = gain(node.right). Both are already clamped at 0. - Update
best = max(best, node.val + left + right). This scores the path that bends at this node. - Return
max(0, node.val + max(left, right))to the parent. Only one arm goes up. - Call
gain(root)once and returnbest. - In Python, Java and JavaScript the code below uses an explicit stack in postorder and a map of finished arms, so a 30000-node chain cannot overflow the call stack.
Dry run
Postorder on [-10, 9, 20, null, null, 15, 7] visits 9, 15, 7, 20, -10. Each row shows the arms received, the bent sum, the global best afterwards, and the arm returned.
| Node | left arm | right arm | bent sum | best after | returned arm |
|---|---|---|---|---|---|
| 9 | 0 | 0 | 9 | 9 | 9 |
| 15 | 0 | 0 | 15 | 15 | 15 |
| 7 | 0 | 0 | 7 | 15 | 7 |
| 20 | 15 | 7 | 42 | 42 | 35 |
| -10 | 9 | 35 | 34 | 42 | max(0, 25) = 25 |
At node 20 the bent sum is 20 + 15 + 7 = 42, and the arm sent up is 20 + max(15, 7) = 35. At the root the bent sum is -10 + 9 + 35 = 34, which does not beat 42. The function returns best = 42.
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) |
Let n be the number of nodes and h the tree height. Each node is entered once, and the work inside is a fixed number of additions and comparisons, so time is O(n). The stack, or call stack in the recursive versions, holds at most one node per level of the current root-to-node path, so it is O(h).
In the explicit-stack versions, the map holds only finished nodes whose parent has not finished, at most one per level, which is also O(h). In a chain h = n, and in a balanced tree h is about log n.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
best = float('-inf')
gain = {} # finished node -> clamped downward arm
stack = [(root, False)]
while stack:
node, done = stack.pop()
if not done:
# revisit this node after both children are finished
stack.append((node, True))
if node.right:
stack.append((node.right, False))
if node.left:
stack.append((node.left, False))
else:
left = gain.pop(node.left, 0)
right = gain.pop(node.right, 0)
# path that bends at this node
best = max(best, node.val + left + right)
# only one arm can go up to the parent
gain[node] = max(0, node.val + max(left, right))
return bestJavaTested in our runner
import java.util.*;
class Solution {
public int maxPathSum(TreeNode root) {
int best = Integer.MIN_VALUE;
Map<TreeNode, Integer> gain = new HashMap<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode cur = root;
TreeNode last = null;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode top = stack.peek();
if (top.right != null && last != top.right) {
cur = top.right;
} else {
stack.pop();
Integer lv = gain.remove(top.left);
Integer rv = gain.remove(top.right);
int l = lv == null ? 0 : lv;
int r = rv == null ? 0 : rv;
// path that bends at this node
best = Math.max(best, top.val + l + r);
// only one arm can go up to the parent
gain.put(top, Math.max(0, top.val + Math.max(l, r)));
last = top;
}
}
return best;
}
}C++Tested in our runner
#include <algorithm>
#include <climits>
class Solution {
int best;
// returns the best clamped arm that starts at n and goes down
int gain(TreeNode* n) {
if (!n) return 0;
int l = gain(n->left);
int r = gain(n->right);
// path that bends at this node
best = std::max(best, n->val + l + r);
// only one arm can go up to the parent
return std::max(0, n->val + std::max(l, r));
}
public:
int maxPathSum(TreeNode* root) {
best = INT_MIN;
gain(root);
return best;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function(root) {
let best = -Infinity;
const gain = new Map(); // finished node -> clamped downward arm
const stack = [];
let cur = root;
let last = null;
while (cur || stack.length > 0) {
while (cur) {
stack.push(cur);
cur = cur.left;
}
const top = stack[stack.length - 1];
if (top.right && last !== top.right) {
cur = top.right;
} else {
stack.pop();
const l = gain.get(top.left) || 0;
const r = gain.get(top.right) || 0;
gain.delete(top.left);
gain.delete(top.right);
// path that bends at this node
best = Math.max(best, top.val + l + r);
// only one arm can go up to the parent
gain.set(top, Math.max(0, top.val + Math.max(l, r)));
last = top;
}
}
return best;
};GoTested in our runner
func maxPathSum(root *TreeNode) int {
maxInt := func(a, b int) int {
if a > b {
return a
}
return b
}
best := root.Val
// returns the best clamped arm that starts at n and goes down
var gain func(n *TreeNode) int
gain = func(n *TreeNode) int {
if n == nil {
return 0
}
l := gain(n.Left)
r := gain(n.Right)
// path that bends at this node
best = maxInt(best, n.Val+l+r)
// only one arm can go up to the parent
return maxInt(0, n.Val+maxInt(l, r))
}
gain(root)
return best
}C#Tested in our runner
public class Solution {
private int best;
// returns the best clamped arm that starts at n and goes down
private int Gain(TreeNode n) {
if (n == null) return 0;
int l = Gain(n.left);
int r = Gain(n.right);
// path that bends at this node
best = Math.Max(best, n.val + l + r);
// only one arm can go up to the parent
return Math.Max(0, n.val + Math.Max(l, r));
}
public int maxPathSum(TreeNode root) {
best = int.MinValue;
Gain(root);
return best;
}
}Common mistakes
- Starting with
best = 0. A tree such as[-3]must return -3, but the code returns 0. Start from the minimum integer, or fromroot.val, so the path is always non-empty. - Returning
node.val + left + rightto the parent. That value describes a bent path, and a parent cannot extend a bent path without visiting the node twice. Returnnode.val + max(left, right)and use the bent sum only forbest. - Skipping the clamp, as in
left = gain(node.left)with nomax(0, ...). A negative subtree then drags down every path above it. Clamp each arm at 0 so the path can stop at the current node. - Clamping the node's own value, for example
best = max(best, max(0, node.val) + left + right). In an all-negative tree this reports a sum that skips the node, which is not a valid path. Only arms are clamped, nevernode.val. - Treating the problem as root-to-leaf or as downward-only paths. The best path can bend at any node and may not touch the root, as in Example 2 where the answer 42 ignores -10. Score the bent sum at every node.
- Updating
bestonly at the root, or only at leaves. The winning bend can sit at any node. Updatebestonce per call, after both children return.
Edge cases
- A single node
[5]returns 5, and[-3]returns -3. The path is the node itself. - All negative values such as
[-2, -1]. The answer is -1, the single best node, because both arms clamp to 0 and no extension helps. - A chain of 30000 nodes. The answer is a downward path with at most one arm per node, and recursive code in Python, Java or JavaScript can overflow the stack, so use an explicit stack there.
- A mix where the best path avoids the root, such as
[-10, 9, 20, null, null, 15, 7]. The answer 42 comes from the subtree at 20. - A negative node between two big positives, such as
[1, -5, 2]read as root 1 with children -5 and 2. The clamp drops -5, and the answer is1 + 2 = 3. - A root with a large negative value above two large positive subtrees. The bent path at the root may lose to a path entirely inside one subtree, so keep the global best across all nodes.
Follow-ups interviewers ask
- What changes if the path must go from the root downward to any node?
- The bend disappears. You only follow one arm from the root, so the answer is
root.val + max(0, best arm)along a single descent, or the maximum over all root-to-node prefix sums if the path can end anywhere. One DFS carrying the running sum computes it in O(n) time. - How would you return the path itself, not only its sum?
- Store, for each node, which child gave the larger arm. Track the node where the best bent sum occurred. Then walk the left arm down from that node, reverse it, add the node, and walk the right arm down. This costs O(n) time and O(h) extra space for the pointers, and it needs a second small traversal after the DFS.
- Can you do it without recursion?
- Yes. Run an iterative postorder with an explicit stack, as in the Python, Java and JavaScript code above. Keep a map from finished node to its clamped arm, and remove a child's entry once its parent has used it. Time stays O(n) and extra space stays O(h). Morris-style traversal could cut the stack. It temporarily rewires the tree and makes postorder awkward.
Binary Tree Maximum Path Sum FAQ
What is the time complexity of Binary Tree Maximum Path Sum?
The one-pass DFS runs in O(n) time, where n is the number of nodes, because each node is processed once with constant work. Space is O(h) for the stack, where h is the height. The brute force that recomputes downward arms for every node is O(n^2) in the worst case.
Why use postorder DFS for Binary Tree Maximum Path Sum?
A node cannot compute its best bent path until it knows the best downward arm of each child. Postorder finishes both children first, so each node reads two ready numbers, scores itself, and returns one number. Preorder or level order would force you to recompute arms.
Why do we clamp child gains at 0?
A negative arm can only reduce a path sum, and a path is allowed to stop at any node. Replacing a negative arm with 0 models the choice not to extend into that child. The node's own value is never clamped, so all-negative trees still return the largest single value.
Why can't the function return the bent path sum to the parent?
A path may not branch. Once a path uses both children of a node, it cannot also continue upward, because the parent would then be adjacent to a node that already has two path neighbours. So the function returns one arm for the parent and keeps the bent sum for the global answer only.
Can Binary Tree Maximum Path Sum be solved in O(1) extra space?
Not with this approach. The DFS needs O(h) space for the call or explicit stack, and h can be n for a chain. A Morris-style traversal can avoid the stack but rewires pointers and complicates the postorder logic, so O(h) is the standard answer.
Why does the Python solution avoid recursion?
Python's default recursion limit is 1000, and the tree can be 30000 nodes deep. Raising the limit works in many setups but can crash on deep chains. An explicit stack with a dictionary of finished arms gives the same O(n) time and avoids the risk.
Asked at
See which companies ask this — Pro
Related problems
- Height of Binary Tree After Subtree Removal Queries · same technique: Recursive Postorder Traversal
- House Robber III · same technique: Recursive Postorder Traversal
- Delete Leaves With a Given Value · same technique: Recursive Postorder Traversal
- All Nodes Distance K in Binary Tree · same technique: Recursive Postorder Traversal
- Find Leaves of Binary Tree · same technique: Recursive Postorder Traversal
- Serialize and Deserialize Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Level Order Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Right Side View · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)