awelgorithms

Tree DP from children

Updated

Solve every child subtree first, then combine those answers at the parent. take[u] uses skip of each child; skip[u] uses max(take,skip) of each child. Postorder (or recursion that returns a pair) is the fill order.

What to focus on

The state lives on a node, not on an array index unless you number the tree. Using a parent before its children reads unsolved subtrees. [4, 1, 9] is root 4 with left 1 and right 9.

Worked examples

house robber tree

a = [4, 1, 9]
  1. leaf 1: take 1 skip 0
  2. leaf 9: take 9 skip 0
  3. root take 4, skip 1+9=10
  4. best 10

Result: 10

take root only

a = [4, 1, 9]
  1. take 4 forbids take 1 and take 9

Result: take[root]=4

one node

a = [4]
  1. take 4, skip 0

Result: 4

Try it

Write treeDp(a). a is a tree of 1 or 3 nodes with positive values. Each node has 0–2 children. take[u] / skip[u] is best in the subtree of u with u taken or skipped. Postorder: children before parent. Return the best at the root. [4, 1, 9]: finish 1 and 9, then 4. Best is skip-root 10. [4] → 4.

The tree is non-empty with 1 or 3 nodes. Values are positive. Each node has 0–2 children.