Blind 75 · #34 · Trees

Binary Tree Maximum Path Sum

HardPost-order DFS with a global bestTime O(n)Space O(h)

Binary Tree Maximum Path Sum is a hard Trees problem from the Blind 75. The key pattern is post-order dfs with a global best, and a good solution runs in O(n) time.

Problem

Return the greatest sum along any non-empty path connected through parent-child edges in the tree.

Examples

Example 1

Input

[-8,4,11,null,null,6,12]

Output

29

Example 2

Input

[2,1,4]

Output

7

Example 3

Input

[-6,5,12,null,null,4,3]

Output

19

Approach

Each node returns the best downward path it can extend, ignoring negative branches, and updates the overall best with value + left gain + right gain.

PatternPost-order DFS with a global best
TimeO(n)
SpaceO(h)

Watch out for

If every value is negative the answer is the largest single node, never 0.

More Trees problems