Binary Tree Maximum Path Sum

Post-order DFS returns the best single-arm gain; meanwhile track the best path bending at any node.

Hard
Time O(n) Space O(h)
LeetCode
3 min read
tree dfs post-order

Problem#

Given the root of a binary tree, return the maximum sum of any path. A path can start and end at any nodes and goes through parent-child connections.

Examples#

  • [1,2,3]6 (2 + 1 + 3)
  • [-10,9,20,null,null,15,7]42 (15 + 20 + 7)

Constraints#

  • The number of nodes is in [1, 3 * 10^4]. -1000 <= Node.val <= 1000.

Approach#

Each path can be decomposed into a “left arm + node + right arm” at its highest node. DFS each node returns the best single-arm gain (max of zero, left arm, right arm — clamping negatives to 0 means skip that branch). Track globally the best bend left + node + right at every node.

Solution#

Binary Tree Maximum Path Sum
class Solution {
public:
int maxPathSum(TreeNode* root) {
int best = INT_MIN;
function<int(TreeNode*)> dfs = [&](TreeNode* u) -> int {
if (!u) return 0;
int l = max(0, dfs(u->left));
int r = max(0, dfs(u->right));
best = max(best, u->val + l + r);
return u->val + max(l, r);
};
dfs(root);
return best;
}
};

Editorial#

The key insight: a single recursive call returns the best path that continues upward through the parent, which forbids using both arms. But at the bend node itself, we can use both. Track the bend value separately while returning only the straight-up extension.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.