DP on trees
On a tree, each node's answer comes from its children's answers in one post-order pass. Return a small tuple per node, such as (best with this node taken, best without it), so the parent can apply its rule. Counting tree shapes is DP over height or size instead.
How to recognise it
- A tree where each node takes part in a choice.
- A rule linking parents and children, such as 'not both chosen'.
- Counting trees of a given height or size.
Two numbers per node
best(n): if null: (0, 0)
(lt, ls) = best(left); (rt, rs) = best(right)
take = 1 + ls + rs # n chosen: children are not
skip = max(lt, ls) + max(rt, rs)
return (take, skip)
The same shape answers House Robber III and other "no parent and child together" questions.
Counting shapes
count(h) = count(h-1)² + 2 × count(h-1) × count(h-2), with count(0) = count(1) = 1.
Common mistakes
- Returning one number when the parent needs two.
- Recursing past the stack limit on a long chain.
Problems
- Count Balanced Binary Trees of Height hmediumguide ready
- Largest Independent Set Problemmediumguide ready