Hard

Binary Tree Maximum Path Sum

Description

Find the largest sum on any nonempty simple path in a nonempty tree; the path need not pass through the root.

Solution

import sys

sys.setrecursionlimit(100_000)

def max_path_sum(root):
    best = float('-inf')
    def gain(node):
        nonlocal best
        if not node:
            return 0
        left, right = max(0, gain(node.left)), max(0, gain(node.right))
        best = max(best, node.val+left+right)
        return node.val + max(left, right)
    gain(root)
    return best

Examples

Inputs are positional arguments. Trees use level-order arrays; linked lists use value arrays. Design problems list operations in order.

Example 1

Input
[[-3]]
Output
-3

The nonempty-path rule requires taking the negative node.

Example 2

Input
[[1,2,3]]
Output
6

The path 2, 1, 3 totals six.

Example 3

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

The best path is 15, 20, 7 and excludes the root.

Approach

Each call returns its best one-branch gain, while a global best can combine both branches through that node.

Time & space

O(n) time; O(h) recursion space. Here n is the node count, and h is the tree height.