Overview
This is DP on Trees. We use a post-order DFS to process children before their parents. At each node, we make decisions based on the max paths coming from its subtrees.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the maximum path sum between ANY two nodes in a binary tree. The path does not need to pass through the root.
This is DP on Trees. We use a post-order DFS to process children before their parents. At each node, we make decisions based on the max paths coming from its subtrees.
If a subtree returns a negative sum, it's better to just not include it. We use `Math.max(0, dfs(child))` to "clip" negative branches.
The highest path sum might arch over the current node, combining both left and right subtrees: `node.val + left + right`. We update `globalMax` with this.
However, when a node returns to its parent, it can only offer ONE path (it can't split). So it returns `node.val + max(left, right)`.