House Robber III
Difficulty: Medium · Pattern: Trees & BST · LeetCode #337
The houses form a binary tree. Robbing two directly linked houses (a parent and its child) on the same night triggers the alarm. Return the maximum amount you can rob.
Examples
text
3
/ \
2 3 → 7 (3 + 3 + 1)
\ \
3 1
[3,2,3,null,3,null,1] → 7
[3,4,5,1,3,null,1] → 9 (4 + 5)Hints
- For each node there are two cases: rob it (then its children must be skipped) or skip it (then each child is free to go either way).
- Return both answers from one DFS call to avoid recomputation.
Approach
Tree DP: dfs(node) returns a pair (withNode, withoutNode):
text
(lw, lo) = dfs(left); (rw, ro) = dfs(right)
withNode = node.val + lo + ro
withoutNode = max(lw, lo) + max(rw, ro)The answer is max(dfs(root)). Plain recursion that tries "rob root vs rob grandchildren" without returning pairs repeats work exponentially. Returning both states makes it one O(n) pass. This is the tree version of 1-D DP: each node's state depends only on its children's states.
Complexity
Time: O(n). Space: O(h).
Python solution
def rob(root):
def dfs(node):
if not node:
return (0, 0)
lw, lo = dfs(node.left)
rw, ro = dfs(node.right)
return (node.val + lo + ro, max(lw, lo) + max(rw, ro))
return max(dfs(root))JavaScript solution
function rob(root) {
const dfs = (node) => {
if (!node) return [0, 0];
const [lw, lo] = dfs(node.left), [rw, ro] = dfs(node.right);
return [node.val + lo + ro, Math.max(lw, lo) + Math.max(rw, ro)];
};
return Math.max(...dfs(root));
}