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
- Print root to leaf path in BTmediumguide ready
- Sum of Nodes on the Longest path from root to leaf nodemediumguide ready
- Print all "K" Sum paths in a Binary treemediumguide ready
- Binary Tree Maximum Path Sumhardguide ready