binary tree (values may be negative)
9
-10
15
20
7
call stack ↓
(returned)
Recursive DFS (post-order gain + global max)
▸1best = −∞2gain(node):3 if node is null: return 04 L = max(gain(node.left), 0) // drop negative arms5 R = max(gain(node.right), 0)6 best = max(best, node.val + L + R) // bend here7 return node.val + max(L, R) // extend parent8// answer = best
state
- goalmax path sum
- global best−∞