Practice · Trees · 12 of 12

Largest Path Sum in a Binary Tree

You are given root, the root of a non-empty binary tree whose values may be negative.

A path is a sequence of nodes, each linked to the next by a parent–child edge, that never visits a node twice. It has at least one node and need not pass through the root. Its sum is the total of its nodes' values.

Return the largest sum of any path.

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
root = [4, -7, 6, 3, 2, 5, -1]
Output
15
The best path is 4 → 6 → 5. Going into the left subtree could only lower the sum.

Example 2

Input
root = [-5, -2, -9]
Output
-2
Every value is negative, so the best path is the single largest node.

Constraints

  • The tree holds 1 to 1000 nodes.
  • Every value is between −1000 and 1000.