House Robber III
Master this topic with zero to advance depth.
House Robber III
Tree robbery.
Level I: Brute Force Recursion
Intuition
Each node can either be robbed or not robbed. If we rob a node, we cannot rob its direct children. If we don't rob it, we can either rob its children or not.
Logic
rob(root) = max(root.val + rob(left.left) + rob(left.right) + rob(right.left) + rob(right.right), rob(left) + rob(right)).
Detailed Dry Run
At root: Option 1 (Rob 1 + grandchildren). Option 2 (Rob children 2 and 3). Max is 3.
Level II: Memoization
Intuition
We can store the result of rob(node) in a HashMap to avoid recomputing for the same node multiple times.
Detailed Dry Run
Store [Node Pointer] -> Max rob value.
Level III: Optimal (Post-order DP Pair)
Intuition
Each node returns a pair: [max if robbed, max if NOT robbed].
- If we rob
root, we must NOT rob its children:root.val + left[1] + right[1]. - If we DON'T rob
root, we take the max of robbing or not robbing each child:max(left) + max(right).
Detailed Dry Run
Leaf returns [val, 0]. Parent returns [parentVal + 0, leafVal + 0].
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.