Binary Tree Maximum Path Sum solution explained

To find the maximum path sum in a binary tree, run a post-order traversal where each node returns the best sum of a path that starts at it and goes down one side, ignoring any child branch whose best sum is negative. At each node, also try the path that bends there (left gain + node + right gain) and keep the largest value seen. That is one visit per node: O(n) time and O(h) extra space.

By Published 7 min read

The problem, in plain terms

Each node of a binary tree holds an integer, possibly negative. A path is a sequence of nodes where each consecutive pair is joined by an edge, and no node appears twice. The path does not have to include the root, does not have to end at a leaf, and may be a single node. Return the largest sum you can get from the values on one path.

Tree A (answer: 18)        Tree B (answer: -2)
      -3                        -4
     /  \                      /  \
    9    4                   -9    -2
        / \
      -6   8

Tree A: 9 -> -3 -> 4 -> 8 = 18
Tree B: every value is negative, so the best path is the single node -2
Two example trees, made up for this page

Tree A shows that a good path can pass through a negative node (the root) when the parts it connects are worth more. Tree B shows the trap of returning zero for an empty path: the path must contain at least one node.

How the problem is used in interviews

This is a favorite harder tree question because the recursive function must return one thing while the answer is another. Candidates who can say clearly "I return the best chain going down, but I record the best path bending here" usually finish it. Interviewers also listen for the negative-value reasoning and for awareness that a deep tree breaks naive recursion.

A slower starting idea

Every path has a single highest node, the point where it bends or starts. So try every node as that top: compute the best downward chain into its left subtree and into its right subtree, add whichever are positive to the node's value, and keep the maximum. Computing a downward chain from scratch is O(size of the subtree), so the total is O(n²) on a chain-shaped tree. It is a good stepping stone because the fast solution is the same idea with the repeated work removed.

def max_path_sum_slow(root):
    def down(node):                     # best downward chain from node
        if node is None:
            return 0
        return node.val + max(0, down(node.left), down(node.right))

    best = root.val
    stack = [root]
    while stack:                        # try every node as the top of the path
        node = stack.pop()
        through = node.val + max(0, down(node.left)) + max(0, down(node.right))
        best = max(best, through)
        stack.extend(c for c in (node.left, node.right) if c)
    return best
Python: try every node as the top. O(n²) in the worst case.

The optimal approach: one post-order pass

Pattern: tree dynamic programming with post-order traversal. Compute the downward chain once per node, bottom up, and reuse the children's results. A helper returns, for each node, its value plus the larger of its children's gains, where a negative gain is replaced by zero (you simply do not extend into that branch). Before returning, the helper updates a running best with the node's value plus both clamped gains, which is the best path whose top is this node.

class Node:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def max_path_sum(root):
    best = root.val                     # any single node is a valid path

    def gain(node):
        """Best sum of a path that starts at node and goes down one side."""
        nonlocal best
        if node is None:
            return 0
        left = max(gain(node.left), 0)  # drop a branch that only hurts
        right = max(gain(node.right), 0)
        best = max(best, node.val + left + right)   # path bending at node
        return node.val + max(left, right)          # path continuing upward

    gain(root)
    return best
Python: post-order recursion with a running best.

Why the return value uses only one side: a parent can only continue the path into one child, otherwise the path would fork. The two-sided sum is valid only as a path that ends its climb at this node, which is exactly what the running best captures.

Recursion depth equals tree height. For a tree shaped like a long chain, Python's default recursion limit of about a thousand frames is too small, so in an interview say that you would raise the limit or use an explicit stack. The C++ version below is iterative for that reason.

#include <algorithm>
#include <climits>
#include <unordered_map>
#include <utility>
#include <vector>

struct Node {
    int val;
    Node* left = nullptr;
    Node* right = nullptr;
    explicit Node(int v) : val(v) {}
};

// Iterative post-order: safe on very deep trees.
long long maxPathSum(Node* root) {
    std::unordered_map<Node*, long long> gain;   // best downward chain per node
    gain[nullptr] = 0;
    long long best = LLONG_MIN;
    std::vector<std::pair<Node*, bool>> stack{{root, false}};
    while (!stack.empty()) {
        auto [node, childrenDone] = stack.back();
        stack.pop_back();
        if (node == nullptr) continue;
        if (!childrenDone) {
            stack.push_back({node, true});       // revisit after the children
            stack.push_back({node->right, false});
            stack.push_back({node->left, false});
            continue;
        }
        long long left = std::max(gain[node->left], 0LL);
        long long right = std::max(gain[node->right], 0LL);
        best = std::max(best, node->val + left + right);
        gain[node] = node->val + std::max(left, right);
    }
    return best;
}
C++17: iterative post-order with a map of gains. Uses long long to avoid overflow on large trees.

Complexity summary

n nodes, tree height h
ApproachTimeExtra space
Try every node as the top, recompute chainsO(n²) worst caseO(h)
Post-order recursion with running bestO(n)O(h) call stack
Iterative post-order with stored gainsO(n)O(n) for the map, O(h) stack
n nodes, tree height h. Scroll sideways on a small screen.

Edge cases to try

  • A single node, positive or negative.
  • Every value negative: the answer is the largest single value, not zero.
  • Every value positive: the answer is the heaviest leaf-to-leaf path through some bend point.
  • A long chain, which turns the problem into the best contiguous run along a line and stresses recursion depth.
  • Zeros mixed with negatives, where clamping at zero and keeping a zero branch give the same result.

Pitfalls

  • Starting the best at zero, which returns 0 for an all-negative tree.
  • Returning node + left + right to the parent, which builds a forked path that is not allowed.
  • Forgetting to clamp negative gains, so a bad branch drags every result down.
  • Assuming the path must go through the root or end at leaves.
  • Using a global variable that is not reset between test cases in a judge or a test harness.

How to explain it out loud

Fictional example

Separating what you return from what you record
Candidate
Every path has one highest node. If I know, for each child, the best chain going down from it, then the best path topped at this node is my value plus the positive parts of both chains.
Candidate
But to my parent I can only offer a chain down one side, so I return my value plus the better child. I record the two-sided total in a running maximum instead.
Candidate
I start that maximum at the root's value, not zero, so an all-negative tree returns its largest node. One post-order pass, O(n) time, O(h) stack.

If you want to test this on trees of your own, Serialize and Deserialize Binary Tree gives you a compact text format to write them in. Construct Binary Tree from Preorder and Inorder is another way to build trees for testing, and practice for recursion with index bounds.

Where Natively fits

This problem rewards saying the two roles of the helper function out loud. While you practice on Mac or Windows, Natively can read the problem from a screenshot, offer coding help on the gain function, and remind you of the all-negative case. It keeps a transcript of the mock round so you can see whether your explanation was clear. Read more about the AI interview assistant.

Questions people ask

How do you solve Binary Tree Maximum Path Sum?

Use a post-order traversal. Each node returns its value plus the better of its children's gains, with negative gains replaced by zero, and updates a running best with its value plus both clamped gains.

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

O(n) time, since each node is processed once, and O(h) extra space for the recursion or explicit stack, where h is the tree height.

Why does an all-negative tree break some solutions?

If the running best starts at zero, the function returns 0 even though a path must contain at least one node. Start it at a real node value instead.

Why can a node return only one child's gain?

A parent can continue a path into only one child. Returning both sides would describe a forked shape, which is not a path.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP