A path in a binary tree is a sequence of nodes where each pair of adjacent nodes has an edge. A node can appear at most once. Given a binary tree, return the maximum path sum of any non-empty path.
DFS: at each node, compute the max gain from left and right subtrees (only positive contributions count). Update global max with left_gain + root.val + right_gain. Return max single-branch gain to parent.
- Global maxSum = Integer.MIN_VALUE.
- dfs(node): if null return 0.
- leftGain = max(0, dfs(left)), rightGain = max(0, dfs(right)).
- Update maxSum = max(maxSum, node.val + leftGain + rightGain).
- Return node.val + max(leftGain, rightGain).
- Time Complexity: O(N)
- Space Complexity: O(H)