Python coding

Heaviest path in a tree

A path in a binary tree is a chain of nodes in which each one is joined to the next by a parent-child link and no node appears twice. It may start and end anywhere, need not pass through the root, and may be a single node. Write max_path_sum(root): return the largest sum of values over all paths. The tree has at least one node and values can be negative. Each TreeNode has val, left and right.

The tests call the provided run_max_path_sum(values), where values lists the tree level by level with null for a missing child: [1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3.

  • run_max_path_sum([2,7,4]) → 13
  • run_max_path_sum([-6,5,9,null,null,8,3]) → 20
  • run_max_path_sum([-4]) → -4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every path has one highest node where it bends: it comes up from one subtree and goes down the other (either side may be empty). Try each node as that top.

Hint 2

Postorder: let gain(node) be the best sum of a path that starts at node and only goes down. A negative gain is worse than taking nothing, so clamp it to 0.

Hint 3

Two values per node: update the answer with val + left + right, but return val + max(left, right), because a path handed to the parent cannot fork. Start the answer at a node's value, not 0.

Solution and why it works
pythonO(n) · O(h), h = height (recursion stack)
# --- your code ---
def max_path_sum(root: "TreeNode") -> int:
    best = root.val

    def gain(node: "TreeNode | None") -> int:
        """Largest sum of a path that starts at `node` and only goes down."""
        nonlocal best
        if node is None:
            return 0
        left = max(gain(node.left), 0)              # a negative branch is better left out
        right = max(gain(node.right), 0)
        best = max(best, node.val + left + right)   # the path that bends at this node
        return node.val + max(left, right)          # a parent can extend one side only

    gain(root)
    return best


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def run_max_path_sum(values: list[int | None]) -> int:
    return max_path_sum(build_tree(values))

Each path has a single topmost node, so try every node as that top: its value plus the best downward branch on each side. gain returns the best sum that starts at a node and goes down one side only, since a path handed to the parent cannot fork; negative branches are clamped to 0, which means leaving them out. Traps: returning val + left + right upward (that is not a path), and starting best at 0, which is wrong when every value is negative.