sagelearnai

Binary Tree Maximum Path Sum

Difficulty: Hard · Pattern: Trees & BST · LeetCode #124

A path is any sequence of nodes connected by edges, with each node used at most once. It need not pass through the root and has at least one node. Return the maximum possible sum of values along any path. Values may be negative.

Examples

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

Hints

  1. For each node, compute the best sum of a path that starts at the node and goes down one side.
  2. A path that "bends" at a node = node + best-down-left + best-down-right, with negative branches dropped (treat them as 0).
  3. Track the global maximum of the bending paths; return only the one-sided path to the parent.

Approach

Define gain(node) = the maximum sum of a downward path starting at node, which is node.val + max(0, gain(left), gain(right)). At each node, a candidate path bends through it: node.val + max(0, gain(left)) + max(0, gain(right)). Update a global best with this candidate. Return the one-sided gain to the parent, since a parent can only extend one branch. Initialize the best to −∞ to handle all-negative trees.

Complexity

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

Python solution
def maxPathSum(root):
    best = float('-inf')
    def gain(node):
        nonlocal best
        if not node:
            return 0
        l = max(gain(node.left), 0)
        r = max(gain(node.right), 0)
        best = max(best, node.val + l + r)
        return node.val + max(l, r)
    gain(root)
    return best
JavaScript solution
function maxPathSum(root) {
  let best = -Infinity;
  const gain = (node) => {
    if (!node) return 0;
    const l = Math.max(gain(node.left), 0), r = Math.max(gain(node.right), 0);
    best = Math.max(best, node.val + l + r);
    return node.val + Math.max(l, r);
  };
  gain(root);
  return best;
}