SDE & MLE Prep

124. Binary Tree Maximum Path Sum

Problem

A path is any sequence of nodes connected by parent-child edges, using each node at most once; it doesn't need to pass through the root and may bend at one node. Return the largest sum of node values over all non-empty paths. Values can be negative.

Example: [-10,9,20,null,null,15,7] → 42 (15 → 20 → 7)

Each node returns the best downward path gain (max(0, left, right) + val, negatives dropped). The best path through the node uses both sides: val + max(0,L) + max(0,R) → update global answer.

     -10
     /  \
    9    20        through 20: 15 + 20 + 7 = 42  (answer)
        /  \       returns up: 20 + 15 = 35
       15   7

Complexity: O(n).

class Solution:
    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        best = float("-inf")

        def gain(node):
            nonlocal best
            if not node:
                return 0
            l, r = max(gain(node.left), 0), max(gain(node.right), 0)
            best = max(best, node.val + l + r)
            return node.val + max(l, r)

        gain(root)
        return best