TRT
Sign in
hardCoreLeetCode#return one, record another#ignore negative branches

Binary tree maximum path sum

Find the path with the largest sum of values anywhere in the tree, returning the best downward branch and recording the best turning path.

The Runtime Theory Team1 min read
Taught inTree recursion patternsPro — members onlyMost tree problems are solved by one of three recursive shapes: combine the children's answers on the way up, pass information down from the root, or return one value while updating a global best.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [1, 2, 3]

out6

inroot = [-10, 9, 20, null, null, 15, 7]

out42

inroot = [-3]

out-3

A path is a sequence of nodes connected by edges, each used at most once; it need not pass through the root. Return the maximum sum of values on any non-empty path.

Before you code

This is the diameter problem with weights. A path turns at some node and uses its best branch on each side. Values can be negative, so a branch can make a path worse.

Hints

  1. gain(node) returns the best sum of a path that starts at node and goes down one side: node.val + max(0, gain(left), gain(right)).
  2. At each node, the best path turning there is node.val + max(0, gain(left)) + max(0, gain(right)). Record the maximum.
  3. Initialize the record to negative infinity, not 0: a tree of all negative values still has a best path.

Production & complexity notes

When solving Binary tree maximum path sum on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Tree recursion patterns to reinforce the underlying pattern.

What it practices

The return-one-record-another shape, from Tree recursion patterns.

Not started

Sign in to save your learning progress.

Sign in to save