Binary Tree Maximum Path Sum

HardTrees

Given the root of a binary tree, choose any chain of nodes joined by edges, each node used at most once. It can be a single node, and it need not touch the root. Return the largest total of values a chain can have.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [-3, 4, -1, 6, 2, null, 5]
Output: 12

The path 6 → 4 → 2 sums to 12 and bends at 4. Going on up through -3 and -1 to 5 gives only 6 + 4 - 3 - 1 + 5 = 11.

Example 2
Input:  root = [-4, 6, 7]
Output: 9

Passing through -4 still pays: 6 + (-4) + 7 = 9, more than 7 alone.

Constraints

  • The tree has 1 to 3 × 10⁴ nodes.
  • -1000 ≤ node.val ≤ 1000

Stuck?

Hint 1

Every path has one highest node, where it bends. At that node, the best path is its value plus the best path down into the left side plus the best path down into the right, and a side that sums below zero is better left out.

Hint 2

Write a recursion that returns the best path going straight down from a node: its value plus the larger of its children’s results, counting a negative result as 0. On the way, update a running best with the path that bends at the node.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur