Skip to content
DSA Patterns
Menu
Language
Tree DFSLC #1245 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Binary Tree Maximum Path Sum

Problem (restated)

A path is any node-to-node sequence. Return the maximum sum of node values along any path (at least one node).

Intuition

From each node, best gain you can offer the parent is val + max(0, best child gain). Also consider path through node using both children for the global answer.

Approaches

Gain DFS + global best

Unverified
Time O(n)Space O(h)

Idea. dfs returns gain upward; update global with leftGain+rightGain+val.

Walkthrough. Negative children are dropped via max(0, …).

Trade-offs. One DFS; careful with all-negative trees (pick largest node).

Solution
Show helper code
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
type Frame = [TreeNode, number, number]; // node, stage, leftGain

export function maxPathSum(root: TreeNode | null): number {
  if (root === null) return 0;
  let best = -Infinity;
  // Frames live only along the current path, so auxiliary space is O(h).
  const stack: Frame[] = [[root, 0, 0]];
  let lastGain = 0;
  while (stack.length > 0) {
    const frame = stack[stack.length - 1];
    const node = frame[0];
    if (frame[1] === 0) {
      frame[1] = 1;
      if (node.left !== null) stack.push([node.left, 0, 0]);
      else frame[2] = 0;
    } else if (frame[1] === 1) {
      if (node.left !== null) frame[2] = lastGain;
      frame[1] = 2;
      if (node.right !== null) stack.push([node.right, 0, 0]);
    } else {
      const left = frame[2];
      const right = node.right !== null ? lastGain : 0;
      best = Math.max(best, node.val + left + right);
      stack.pop();
      lastGain = Math.max(0, node.val + Math.max(left, right));
    }
  }
  return best;
}
type Frame = [TreeNode, number, number]; // node, stage, leftGain

export function maxPathSum(root: TreeNode | null): number {
  if (root === null) return 0;
  let best = -Infinity;
  // Frames live only along the current path, so auxiliary space is O(h).
  const stack: Frame[] = [[root, 0, 0]];
  let lastGain = 0;
  while (stack.length > 0) {
    const frame = stack[stack.length - 1];
    const node = frame[0];
    if (frame[1] === 0) {
      frame[1] = 1;
      if (node.left !== null) stack.push([node.left, 0, 0]);
      else frame[2] = 0;
    } else if (frame[1] === 1) {
      if (node.left !== null) frame[2] = lastGain;
      frame[1] = 2;
      if (node.right !== null) stack.push([node.right, 0, 0]);
    } else {
      const left = frame[2];
      const right = node.right !== null ? lastGain : 0;
      best = Math.max(best, node.val + left + right);
      stack.pop();
      lastGain = Math.max(0, node.val + Math.max(left, right));
    }
  }
  return best;
}

Template connection

The value returned upward is val + max(leftGain, rightGain, 0). A bend through the node, val + leftGain + rightGain with each gain floored at 0, updates a global best. The parent receives a single downward chain.

Notes

A path can bend through a node using both children, but a value returned to the parent can only include one side (or none). So each DFS call:

  1. Computes leftGain = max(0, dfs(left)) and rightGain similarly (drop negative gains).
  2. Updates global best with val + leftGain + rightGain (path through this node).
  3. Returns val + max(leftGain, rightGain) (best chain upward).

All-negative trees: the best path is the largest single node (gains of 0 never add children).

Reflection

  • The value you hand to your parent is one arm: node + max(0, left, right). Both arms cannot climb.
  • The best path through this node is the node plus the left gain plus the right gain. A negative arm counts as 0.
  • All negative: the answer is the largest single node. If a child shrinks the path, leave it off.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Max path sum on −10 / 9, 20 / 15, 7. A path may bend through both children; the value returned to the parent may use only one side.

-10start920157

gain up = val + max(0, best child)

Key:CurrentActive rangeMatchSettled