gain(n) = n.val + max(0, gain(left), gain(right)) restricted to one side; best = max(best, n.val + max(0, gainL) + max(0, gainR)).
Approach 1
class Solution {
private int best = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
gain(root);
return best;
}
private int gain(TreeNode n) {
if (n == null) return 0;
int l = Math.max(0, gain(n.left));
int r = Math.max(0, gain(n.right));
best = Math.max(best, n.val + l + r); // path bending at n
return n.val + Math.max(l, r); // one side only for the parent
}
}
Verdict: One post-order pass.
Before you submit
Edge cases and common mistakes
Test these inputs
All negative (answer is the largest single node)
Single node
Mistakes people make
Starting best at 0 (wrong for all-negative trees).