← DSA
HARD

Binary Tree Maximum Path Sum

PracticeNeetCode ↗LeetCode ↗

Given the root of a binary tree, return the maximum sum of any path between any two nodes. A path doesn't need to pass through the root, and each node can appear in it at most once.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Keep a variable best = -infinity outside the recursion.
  2. Define gain(node); base case None returns 0.
  3. Recursively compute left_gain = max(gain(node.left), 0) and right_gain = max(gain(node.right), 0), clamped at 0 to drop negative branches.
  4. Update best = max(best, node.val + left_gain + right_gain) — the path that uses both branches through this node.
  5. Return node.val + max(left_gain, right_gain) as the best single branch this node offers its parent; call gain(root) once and return best.

Complexity

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

Code

def maxPathSum(root: TreeNode | None) -> int:
    best = float("-inf")

    def gain(node: TreeNode | None) -> int:
        nonlocal best
        if not node:
            return 0
        left_gain = max(gain(node.left), 0)
        right_gain = max(gain(node.right), 0)
        best = max(best, node.val + left_gain + right_gain)
        return node.val + max(left_gain, right_gain)

    gain(root)
    return best

Code Explanation

How the solution above works, piece by piece.

  1. gain(node) returns the best sum of a path that starts at node and goes down one side.
  2. max(gain(child), 0): a negative branch is dropped rather than added.
  3. node.val + left_gain + right_gain is the best path that bends at this node; update best.
  4. Return node.val + max(left_gain, right_gain): a path continuing to the parent can use only one child.
  5. best starts at −∞ so trees with only negative values work. O(n) time, O(height) stack.

Visual Walkthrough

Running it on root = [-10, 9, 20, null, null, 15, 7]:

Maximum path 15 to 20 to 7-10920157gain 25gain 9gain 35gain 15gain 7best path bends at 20:15 + 20 + 7 = 42at −10: −10 + 9 + 35 = 34 < 42gain = best one-sided path up
Under each node is the gain it reports upward: its value plus its better child (negative gains are replaced by 0). The best total uses both children at one node, here 15 + 20 + 7 = 42; including −10 would only lower it.
best pathnot worth including

Video Explanation

NeetCode — Binary Tree Maximum Path Sum, LeetCode 124