Binary Tree Maximum Path Sum

50 min · maxPathSum()

Picture each tree node as a checkpoint that adds points or charges a cost. The richest route may climb out of one branch, cross the node where two branches meet, and finish in another without ever touching the root.

A path is a sequence of nodes where each neighboring pair shares an edge. Given the root of a non-empty binary tree, return the largest sum you can collect along any path.

A few ground rules:

  • A path may start and end at any nodes.
  • Each node may appear at most once, so the route can't turn around and revisit ground.
  • The path doesn't have to include the root or a leaf.
  • A path must contain at least one node. If every value is negative, you still choose one of them rather than taking an empty route worth zero.

Constraints

  • 1 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000
  • root is never null.

Hints

Stand at one node

A path that bends through the current node may collect one useful contribution from the left child and one from the right child. What should happen to a contribution whose total is negative?

What can travel upward?

A parent can extend only one branch from its child. Returning both branches would create a fork, not a path. Keep the better single branch for the parent, but test both branches together as an answer at the current node.

Zero is useful, but not an answer

Clamp a harmful child contribution to zero. Keep the global answer initialized to a real node value, though, or an all-negative tree will incorrectly return the empty path.

Follow-up

How would you return the actual sequence of nodes on a maximum-sum path while keeping the same O(n) running time?

Visible cases

Examples

Example 1

ready
Input
root = [
  1,
  2,
  3
]
Expected
6
Why
the route 2 → 1 → 3 collects all three values

Example 2

ready
Input
root = [
  -10,
  9,
  20,
  null,
  null,
  15,
  7
]
Expected
42
Why
15 → 20 → 7 wins without visiting the root

Example 3

ready
Input
root = [
  -3
]
Expected
-3
Why
a path can't be empty, so the lone negative node is the answer

Interview signal

Asked at

AmazonMetaGoogleDoorDash
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite