Skip to problem
←

Binary Tree Maximum Path Sum

Hard 0 attempts

You're given the root of a binary tree. A path is any non-empty sequence of nodes connected edge to edge, visiting each node at most once, and it isn't required to start or end at the root or pass through it. Find the path whose node values sum to the largest total, and return that sum.

Function contract

Implement maxPathSum(root). The runner converts the level-order input array into nodes with val, left, and right fields; [] becomes null.

Output: The largest sum along a non-empty path of distinct, edge-connected nodes. The path may begin and end anywhere in the tree.

Example 1

Input
root = [-10,9,20,null,null,15,7]
Output
42

Example 2

Input
root = [-3]
Output
-3
Visual Aid
The best path need not include the root
-1092015715 + 20 + 7 = 42

The highlighted path uses both children of 20 and skips the negative root.

Constraints
  • 1 <= number of nodes <= 3 * 10^4
  • -1000 <= Node.val <= 1000

Iterative Postorder

For each node, retain the best downward path. Its best full path combines the node with positive gains from both children; the downward value passed to its parent uses only one child.

javascript
function maxPathSum(root) {
  if (!root) return 0;
  const order = [],
    stack = [root];
  while (stack.length) {
    const node = stack.pop();
    order.push(node);
    if (node.left) stack.push(node.left);
    if (node.right) stack.push(node.right);
  }
  const gains = new Map();
  let best = -Infinity;
  for (let i = order.length - 1; i >= 0; i--) {
    const node = order[i],
      l = Math.max(0, gains.get(node.left) || 0),
      r = Math.max(0, gains.get(node.right) || 0);
    best = Math.max(best, node.val + l + r);
    gains.set(node, node.val + Math.max(l, r));
  }
  return best;
}

Time: O(n) | Space: O(n) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript