Example 1
- Input
- root = [-10,9,20,null,null,15,7]
- Output
- 42
The best path is 15 -> 20 -> 7. Including the root would produce at most 34, so a path entirely below the root wins.
A path is any connected sequence of nodes where none repeats. Given the root of a binary tree with possibly negative values, return the largest sum over all non-empty paths, which need not pass through the root.
A path in a binary tree is a sequence of nodes where each pair of consecutive nodes is joined by an edge, and no node repeats.
Given the root of a binary tree, return the maximum sum over all non-empty paths. The best path may start and end anywhere and does not need to pass through the root.
[1, 30000].-1000 <= Node.val <= 1000The best path is 15 -> 20 -> 7. Including the root would produce at most 34, so a path entirely below the root wins.
The path must contain a node. The only valid choice is -3; an empty path with sum zero is not allowed.
Every extra node makes a path worse. Choose the least negative single node, -3, rather than clamping the final answer to zero.
Both child branches help: the path 2 -> 1 -> 3 sums to 6. The downward gain from root is only 4, illustrating why returning the root gain alone loses the answer.
The left child has a complete two-branch path of sum 9, but only its gain 7 can extend to 5. The legal winning path is 3 -> 4 -> 5, sum 12; adding both grandchildren and 5 would create an illegal fork.
A path can rise toward the root and then descend, but it cannot fork into three branches. Call its highest node the peak. At a peak, combine the node value with the best useful downward path from each child; a negative child contribution is better omitted. In Example 1, peak 20 combines 15 and 7 for 42. Its parent can extend only one of those branches, so 20 offers a gain of 35, not 42. This difference between a complete path and an extendable gain is the central invariant.
Reveal Peak at Every Node: intuition, complexity, and code
For tree path problems, distinguish the complete candidate that may use both children from the extendable gain that may use only one. Evaluate the candidate at every node, then use postorder to compute gains once and reuse them above. Explicit traversal stacks preserve this invariant without recursion depth limits.