Skip to content
Problem · Canonical Warm-Up
hardpost-order · return-up · global-maxTime · O(n)Space · O(h)

Binary Tree Maximum Path Sum

Problem statement

Statement

A path in a binary tree is a sequence of nodes where consecutive nodes are joined by an edge, and no node appears twice. The path need not pass through the root and need not touch a leaf. Given the root of a binary tree, return the largest sum achievable by any non-empty path.

Examples

    1
   / \
  2   3
root = [1, 2, 3]
-> 6                 (2 -> 1 -> 3, an arch through the root)

     -10
     /  \
    9   20
       /  \
      15   7
root = [-10, 9, 20, null, null, 15, 7]
-> 42                (15 -> 20 -> 7; the best path never touches the root)

root = [-3]
-> -3                (paths are non-empty, so a single negative node is the answer)

    2
   /
  -1
root = [2, -1]
-> 2                 (the negative child is simply not taken)

Constraints

  • The tree holds between 1 and 3 * 10^4 nodes.
  • -1000 <= Node.val <= 1000, so values may be negative and the answer may be negative.
  • A single node counts as a valid path of length one.

What this problem is really testing

Whether you can hold two different quantities in one recursive function without conflating them. That is the entire difficulty, and it is a genuine step up from tree problems where the recursion returns the answer directly.

Consider what a path looks like at its topmost node. It comes up from the left subtree, crosses the node, and descends into the right subtree: an arch. That arch is a perfectly good candidate for the global answer. But it cannot be handed to the parent, because a parent that extends an arch would create a fork, and a fork is not a path. What the parent can use is a single arm: the node plus its better side, a shape that still has a free end to attach to.

So every call produces two things. The arch is recorded against a running global maximum and then discarded. The arm is returned upward. Candidates who return the arch get answers that are too large and structurally impossible; candidates who record only the arm miss every answer whose best path turns at some node. Keeping the two separate, and being able to say why they differ, is the whole interview.

The clarifying image is a river system. Water in a tributary can only flow one way into the main channel, which is the arm being returned. But standing at a confluence you can measure the combined flow of two tributaries meeting, which is the arch being recorded. You measure at every confluence; you only ever send one channel downstream.