Blind 75 · Trees

Binary Tree Maximum Path Sum

Hard

Watch the walkthrough (6:35)

Problem

A path in a binary tree is a chain of nodes, each joined to the next by an edge, with no node used twice.
A path can start and end at any node: it does not have to pass through the root, or reach a leaf.
Given the root, return the largest sum of the values on any path.
A path has at least one node.

Examples

Example 1:
Input: root = [1,2,3]
Output: 6

Example 2:
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: 15 + 20 + 7 — the best path never touches the root.

Example 3:
Input: root = [-3]
Output: -3

Example 4:
Input: root = [2,-1]
Output: 2

Constraints

1 <= number of nodes <= 3 * 10^4
-1000 <= Node.val <= 1000

Prerequisites

Binary trees, and recursion over them: solve the children, combine, return. The base case is almost always the empty tree.
Depth-first order (pre, in, post) and breadth-first by level — and knowing which one a problem is really asking for.

How to think about it

1. Two Roles for Every Node Optimal

Intuition

Each node plays two parts, and keeping them apart is the entire problem. As a PASS-THROUGH it hands its parent a chain: itself plus at most ONE child's contribution, because a path cannot fork and still continue upward. As a SUMMIT it may join both children and go no higher — that is where the best answer might live. So the recursion returns the pass-through value while a running best records every summit. A negative contribution is dropped to zero: a path may simply decline to include it.

Algorithm

1. An empty node contributes nothing.
2. Take each child's contribution, clamped at zero.
3. The summit through this node is its value plus both contributions — offer that to the running best.
4. Return this node's value plus the LARGER single contribution, which is what its parent can use.

Time & Space

Time O(n). Space O(h). Seed the best with the root's own value: a single node is a path, so an all-negative tree still answers with its least-bad node.

2. The Running Best From Minus Infinity

Intuition

The same walk, with the running best started at negative infinity rather than at the root's value, and in Python the helper nested inside maxPathSum, where it reads and sets self.best. Any node's own value beats negative infinity, so the first summit replaces it, and the answer is the same. The first approach starts best at the root's value, since one node is a path, and makes the helper a method of its own.

Algorithm

1. An empty node contributes nothing.
2. Take each child's contribution, clamped at zero.
3. The summit through this node is its value plus both contributions — offer that to the running best.
4. Return this node's value plus the LARGER single contribution, which is what its parent can use.

Time & Space

Time O(n). Space O(h). Seed the best at negative infinity so an all-negative tree still answers with its least-bad node.