House Robber III
LeetCode 337 · Medium · solution, intuition & step-by-step walkthrough
State (node, can_rob); robbing forbids the children.
This is how I solved House Robber III (LeetCode 337), a medium problem from the Tree DP pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Same rob/skip choice as House Robber, but on a tree: if you rob a node you can't rob its children; if you skip it, each child is free to be robbed or not. Memoise on (node, can_rob).
Approach
- 1
dfs(node, can_rob): None → 0.
- 2
can_rob: max(node + children not robbed, children free).
- 3
can't rob: both children free.
- 4
Answer = max of both states at the root.
How I solved it
Tree DP with memoPythonO(n) time · O(n) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
memo={}
def dfs(node,can_rob):
key = (id(node),can_rob)
if node==None:
return 0
if key in memo:
return memo[key]
if can_rob:
rob = node.val+dfs(node.left,False)+dfs(node.right,False)
dontrob=dfs(node.left,True)+dfs(node.right,True)
memo[key]= max(rob,dontrob)
return memo[key]
else:
memo[key]=dfs(node.left,True)+dfs(node.right,True)
return memo[key]
return max(dfs(root,True),dfs(root,False))House Robber III — FAQ
What is the intuition behind House Robber III?
Same rob/skip choice as House Robber, but on a tree: if you rob a node you can't rob its children; if you skip it, each child is free to be robbed or not. Memoise on (node, can_rob).
How do you solve House Robber III (LeetCode 337)?
1. dfs(node, can_rob): None → 0. 2. can_rob: max(node + children not robbed, children free). 3. can't rob: both children free. 4. Answer = max of both states at the root.
What is the time and space complexity of House Robber III?
Time: O(n). Space: O(n). (Accepted approach: Tree DP with memo.)
What are common mistakes in House Robber III?
Returning a (rob, skip) pair per node avoids the memo dictionary entirely.