mediumTreeDynamic ProgrammingTrees

House Robber III

mediumTime: O(n)Space: O(h)

Recognize the pattern

rob houses in a treecan't rob parent and childtree DP

Brute force idea

If you approach House Robber III in the most literal way possible, you get this: Try all subsets of non-adjacent nodes. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in House Robber III comes when you notice this: DFS returning two values per node: (rob this node, skip this node). Rob = node.val + skip(left) + skip(right). Skip = max(rob, skip) of left + max(rob, skip) of right. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

At the center of House Robber III is one steady idea: Each node has two choices: rob it (can't rob children) or skip it (children can be robbed or skipped). The dual return value lets the parent make the optimal choice. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

A common way to get lost in House Robber III is this: Using memoization with node references — works but the dual-return DFS is cleaner. Also, not returning both values forces redundant subtree computation. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Trees Pattern