Learn / Trees

Path sums

Root-to-leaf paths are a depth-first walk that carries the path so far and undoes the last step on the way back. Paths that may start anywhere going down are counted with prefix sums along the current root path. Paths that may bend use the 'gain' trick: each node returns the best one-sided path to its parent and records the best two-sided one.

How to recognise it

  • Paths from the root to the leaves, or any downward path.
  • A target sum, or the largest sum.
  • A path may bend at one node (go up then down).

Carrying the path

walk(n, path):
    if n is null: return
    path.append(n.val)
    if n is a leaf: record a copy of path
    walk(n.left, path); walk(n.right, path)
    path.pop()                  # undo

What a node, a child, a leaf and a level are is on the Structures page.

Downward paths with a target sum

Keep a map of prefix sums on the path from the root to the current node. A downward path ending here has sum k exactly when an earlier prefix equals prefix - k. Add the current prefix before going into the children, and remove it on the way back.

Paths that bend

gain(n):
    l = max(0, gain(n.left)); r = max(0, gain(n.right))
    best = max(best, n.val + l + r)      # bend here
    return n.val + max(l, r)              # one side only, for the parent

Common mistakes

  • Sharing one path list without undoing, so paths leak into each other.
  • Forgetting that a single negative node may be the whole answer in Maximum Path Sum.

Problems

0 of 4 solved

Check yourself

When walking root-to-leaf paths, why remove the last value after the children?

Counting downward paths with sum k, what do you look up at each node?

In Maximum Path Sum, why use max(0, gain(child))?