Maximum-weight independent set (House Robber III). At each node we keep two values: incl (best if the node is chosen) and excl (best if skipped). Leaves first, parents last.
function dfs(v, parent): # post-order DFS excl = 0 # best if v is NOT chosen incl = w[v] # best if v IS chosen for child c in adj[v]: if c == parent: continue # don't walk back up dfs(c, v) # solve child's subtree first excl += max(excl[c], incl[c]) # child free to pick incl += excl[c] # v chosen => child excluded return (excl, incl) # summary for parent # answer = max(dfs(root, -1))
Nodes are folded leaves-first; each turns green when its (excl, incl) is final.
excl value; a node that is excluded lets each child take max(excl, incl).
Each subtree is solved exactly once, so the whole DFS is O(n). See junior.md and professional.md for the correctness proof.