15% off all plans & roadmaps Use code

See plans

Binary Tree Maximum Path Sum

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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Keep a variable best, starting at the smallest possible integer.
  2. Visit every node with any traversal. Call the visited node u.
  3. Compute left = max(0, down(u.left)) and right = max(0, down(u.right)).
  4. Compute the bent path sum u.val + left + right and update best.
  5. Define down(n) as 0 for null, otherwise n.val + max(0, down(n.left), down(n.right)).
  6. Return best after 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

TimeO(n^2)
SpaceO(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 best
Recursive Postorder Traversal pattern infographic for Binary Tree Maximum Path Sum

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

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

  1. Set best to the smallest possible integer. A global or field works.
  2. Define gain(node). For null, return 0.
  3. Compute left = gain(node.left) and right = gain(node.right). Both are already clamped at 0.
  4. Update best = max(best, node.val + left + right). This scores the path that bends at this node.
  5. Return max(0, node.val + max(left, right)) to the parent. Only one arm goes up.
  6. Call gain(root) once and return best.
  7. 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.

Nodeleft armright armbent sumbest afterreturned arm
900999
1500151515
7007157
20157424235
-109353442max(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

TimeO(n)
SpaceO(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 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 from root.val, so the path is always non-empty.
  • Returning node.val + left + right to the parent. That value describes a bent path, and a parent cannot extend a bent path without visiting the node twice. Return node.val + max(left, right) and use the bent sum only for best.
  • Skipping the clamp, as in left = gain(node.left) with no max(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, never node.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 best only at the root, or only at leaves. The winning bend can sit at any node. Update best once 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 is 1 + 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

Practise it