15% off all plans & roadmaps Use code
See plansHouse Robber III
- LeetCode 337
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Recursive Postorder Traversal
Updated
TL;DR: Pick houses in a binary tree to maximize loot, with no parent and child both robbed. Each node reports two totals to its parent, the best with and without itself, computed in one postorder pass.
Problem
The thief has found a new place for his thievery. There is only one entrance to this area, called root.
Each house has exactly one parent, except the root. The houses form a binary tree. The police are alerted if two directly linked houses are robbed on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Example 1
Input: root = [3,2,3,null,3,null,1] Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2
Input: root = [3,4,5,1,3,null,1] Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
Constraints
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^4
Constraints that matter
- Up to 10^4 nodes rules out the exponential recursion that recomputes subtrees, which blows up on a chain.
- A chain can be 10^4 nodes deep, so recursion depth can exceed Python's default limit of 1000. Use an iterative order or raise the limit.
- Values are at most 10^4 and there are at most 10^4 nodes, so totals stay under 10^8. That fits in a 32-bit int.
- Values are non-negative, so a child's larger option is never worse to take. The parent can always pick the best of each child independently.
Hints
Hint 1
This is a tree DP problem.
Hint 2
Write the two choices directly.
Solution
Intuition
This is a tree DP problem. The pattern is Tree DFS with a postorder traversal, where a node's answer is built from its children's answers. The only rule links a house to its parent and its direct children. So each subtree only has to report what it contributes at its own root.
Picture a company where each team lead sends the boss two budgets: one if the lead's team is funded, and one if it is not. Each lead is a node, the funded budget is the rob value, and the boss reads each pair exactly once.
At each node the thief has two choices. Rob the node, which forces both children to be skipped. Or skip the node, which lets each child be robbed or skipped, whichever pays more. Each child therefore needs to report two numbers: its best total when it is robbed, and its best total when it is skipped.
Postorder fits because the parent needs both children's pairs before it can decide. Each node is handled once after its children, so the total work grows linearly with the tree size.
Worked example
Input: root = [3, 2, 3, null, 3, null, 1] Output: 7 Explanation: The thief robs the root (3), the 3 under the left child 2, and the 1 under the right child 3. The root is linked only to 2 and to the right 3, so neither of those is robbed. The three robbed houses are never directly linked, and no better set exists. The total is 3 + 3 + 1 = 7.
Approach 1: Brute force recursion
Write the two choices directly. For a node, either rob it and add the best from its four grandchildren, or skip it and take the best from its two children. Each call returns the larger of the two options.
The recursion never stores anything. A child's answer is computed by the parent call and again by the child's own call, so the same subtree is solved many times.
Steps
- Return 0 when the node is null.
- Start rob_here at node.val, then add rob of each grandchild through the left and right children, skipping null children.
- Set skip_here to rob(node.left) plus rob(node.right).
- Return the larger of rob_here and skip_here.
- Call the function on the root and return the result.
Dry run
Call rob on the root A (3). Its left child is B (2), whose right child is C (3). Its right child is D (3), whose right child is E (1).
rob_here = 3 + rob(B.left) + rob(C) + rob(D.left) + rob(E) = 3 + 0 + 3 + 0 + 1 = 7.
skip_here = rob(B) + rob(D). Then rob(B) = max(2, 3) = 3 and rob(D) = max(3, 1) = 3, so skip_here = 6.
The root returns max(7, 6) = 7. Notice that rob(C) runs twice, once as a grandchild of A and once inside rob(B). The call rob(E) also runs twice, once directly and once inside rob(D).
Complexity
| Time | Exponential in n, O(1.618^n) on a chain |
|---|---|
| Space | O(H) recursion stack, where H is the height |
Let n be the number of nodes. On a chain, rob(node) calls rob on its child and on its grandchild, so T(n) = T(n-1) + T(n-2) + O(1). That is the Fibonacci recurrence, which grows like 1.618 to the power n. The call stack holds one frame per level on the current path, so the space is the height H, which is at most n.
PythonTested in our runner
from typing import List, Optional
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# Start with the root robbed, then add the grandchildren
rob_here = root.val
if root.left:
rob_here += self.rob(root.left.left) + self.rob(root.left.right)
if root.right:
rob_here += self.rob(root.right.left) + self.rob(root.right.right)
# Skip the root, so both children are free to choose
skip_here = self.rob(root.left) + self.rob(root.right)
return max(rob_here, skip_here)JavaTested in our runner
class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
// Rob the root, then add the grandchildren
int robHere = root.val;
if (root.left != null) {
robHere += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
robHere += rob(root.right.left) + rob(root.right.right);
}
// Skip the root, so both children are free to choose
int skipHere = rob(root.left) + rob(root.right);
return Math.max(robHere, skipHere);
}
}C++Tested in our runner
class Solution {
public:
int rob(TreeNode* root) {
if (!root) {
return 0;
}
// Rob the root, then add the grandchildren
int robHere = root->val;
if (root->left) {
robHere += rob(root->left->left) + rob(root->left->right);
}
if (root->right) {
robHere += rob(root->right->left) + rob(root->right->right);
}
// Skip the root, so both children are free to choose
int skipHere = rob(root->left) + rob(root->right);
return robHere > skipHere ? robHere : skipHere;
}
};JavaScriptTested in our runner
var rob = function(root) {
if (!root) {
return 0;
}
// Rob the root, then add the grandchildren
let robHere = root.val;
if (root.left) {
robHere += rob(root.left.left) + rob(root.left.right);
}
if (root.right) {
robHere += rob(root.right.left) + rob(root.right.right);
}
// Skip the root, so both children are free to choose
const skipHere = rob(root.left) + rob(root.right);
return Math.max(robHere, skipHere);
};GoTested in our runner
func rob(root *TreeNode) int {
if root == nil {
return 0
}
// Rob the root, then add the grandchildren
robHere := root.Val
if root.Left != nil {
robHere += rob(root.Left.Left) + rob(root.Left.Right)
}
if root.Right != nil {
robHere += rob(root.Right.Left) + rob(root.Right.Right)
}
// Skip the root, so both children are free to choose
skipHere := rob(root.Left) + rob(root.Right)
if robHere > skipHere {
return robHere
}
return skipHere
}C#Tested in our runner
public class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
// Rob the root, then add the grandchildren
int robHere = root.val;
if (root.left != null) {
robHere += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
robHere += rob(root.right.left) + rob(root.right.right);
}
// Skip the root, so both children are free to choose
int skipHere = rob(root.left) + rob(root.right);
return Math.Max(robHere, skipHere);
}
}The Recursive Postorder Traversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Recursive Postorder Traversal
Approach 2: One postorder pass returning two valuesOptimalRecursive Postorder Traversal
What is slow: the brute force asks the same question about the same node from several calls. Each child's answer is needed by its parent in two forms, and the brute force recomputes both forms every time.
The insight that fixes it: return both values from one call. A node's function returns a pair, the best total when the node is robbed and the best total when it is skipped. The parent reads each child's pair once, so every node is solved exactly once.
Why it is correct. Each returned pair holds the best total for that subtree under both possible states of the node. Any valid robbery either takes the node, forcing children to skip, or leaves it, letting children choose freely, so both cases are covered. Since each child's pair is exact, the parent's maximum is exact too, so the root's larger value is the true optimum.
Steps
- Visit the children before the parent, which is postorder.
- For a null child, use the pair (0, 0).
- Read each child's pair as (rob, skip).
- Set rob_here to node.val + left skip + right skip.
- Set skip_here to max(left rob, left skip) + max(right rob, right skip).
- Return the pair (rob_here, skip_here) for the node.
- At the root, return the larger value of its pair.
Dry run
Postorder visits the nodes in the order C, B, E, D, A. Each row shows the pairs the node reads from its children, then the pair it returns.
| Step | Node | Left pair (rob, skip) | Right pair (rob, skip) | rob_here | skip_here | Stored pair |
|---|---|---|---|---|---|---|
| 1 | C (3) | (0, 0) | (0, 0) | 3 | 0 | (3, 0) |
| 2 | B (2) | (0, 0) | (3, 0) | 2 | 3 | (2, 3) |
| 3 | E (1) | (0, 0) | (0, 0) | 1 | 0 | (1, 0) |
| 4 | D (3) | (0, 0) | (1, 0) | 3 | 1 | (3, 1) |
| 5 | A (3) | (2, 3) | (3, 1) | 7 | 6 | (7, 6) |
The root pair is (7, 6), so the answer is max(7, 6) = 7. Each node appears exactly once in the table.
Complexity
| Time | O(n) |
|---|---|
| Space | O(H) recursion stack, where H is the height; O(n) in the iterative Python version |
Let n be the number of nodes. Each node runs its body once, and the body does constant work after its two children return, so the total work is a constant times n. The recursion keeps one frame per node on the current root-to-leaf path, which is H. The iterative Python version stores one pair per node, so its extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# Collect nodes so every parent comes before its children
order = []
stack = [root]
while stack:
node = stack.pop()
order.append(node)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
# Walking the list backwards handles each child before its parent
pair = {} # node -> (rob_here, skip_here)
for node in reversed(order):
left_rob, left_skip = pair.get(node.left, (0, 0))
right_rob, right_skip = pair.get(node.right, (0, 0))
rob_here = node.val + left_skip + right_skip
skip_here = max(left_rob, left_skip) + max(right_rob, right_skip)
pair[node] = (rob_here, skip_here)
return max(pair[root])JavaTested in our runner
class Solution {
public int rob(TreeNode root) {
int[] result = dfs(root);
return Math.max(result[0], result[1]);
}
// result[0] = best with this node robbed, result[1] = best with it skipped
private int[] dfs(TreeNode node) {
if (node == null) {
return new int[]{0, 0};
}
int[] left = dfs(node.left);
int[] right = dfs(node.right);
// Robbing this node forces both children to be skipped
int robHere = node.val + left[1] + right[1];
// Skipping this node lets each child take its better option
int skipHere = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return new int[]{robHere, skipHere};
}
}C++Tested in our runner
class Solution {
public:
int rob(TreeNode* root) {
pair<int, int> result = dfs(root);
return result.first > result.second ? result.first : result.second;
}
private:
// first = best with this node robbed, second = best with it skipped
pair<int, int> dfs(TreeNode* node) {
if (!node) {
return {0, 0};
}
pair<int, int> left = dfs(node->left);
pair<int, int> right = dfs(node->right);
// Robbing this node forces both children to be skipped
int robHere = node->val + left.second + right.second;
// Skipping this node lets each child take its better option
int leftBest = left.first > left.second ? left.first : left.second;
int rightBest = right.first > right.second ? right.first : right.second;
int skipHere = leftBest + rightBest;
return {robHere, skipHere};
}
};JavaScriptTested in our runner
var rob = function(root) {
// Returns [best with node robbed, best with node skipped]
const dfs = (node) => {
if (!node) {
return [0, 0];
}
const left = dfs(node.left);
const right = dfs(node.right);
// Robbing this node forces both children to be skipped
const robHere = node.val + left[1] + right[1];
// Skipping this node lets each child take its better option
const skipHere = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return [robHere, skipHere];
};
const result = dfs(root);
return Math.max(result[0], result[1]);
};GoTested in our runner
func rob(root *TreeNode) int {
maxInt := func(a, b int) int {
if a > b {
return a
}
return b
}
var dfs func(node *TreeNode) (int, int)
dfs = func(node *TreeNode) (int, int) {
if node == nil {
return 0, 0
}
leftRob, leftSkip := dfs(node.Left)
rightRob, rightSkip := dfs(node.Right)
// Robbing this node forces both children to be skipped
robHere := node.Val + leftSkip + rightSkip
// Skipping this node lets each child take its better option
skipHere := maxInt(leftRob, leftSkip) + maxInt(rightRob, rightSkip)
return robHere, skipHere
}
robRoot, skipRoot := dfs(root)
return maxInt(robRoot, skipRoot)
}C#Tested in our runner
public class Solution {
public int rob(TreeNode root) {
(int robRoot, int skipRoot) = Dfs(root);
return Math.Max(robRoot, skipRoot);
}
// Item1 = best with this node robbed, Item2 = best with it skipped
private (int, int) Dfs(TreeNode node) {
if (node == null) {
return (0, 0);
}
var (leftRob, leftSkip) = Dfs(node.left);
var (rightRob, rightSkip) = Dfs(node.right);
// Robbing this node forces both children to be skipped
int robHere = node.val + leftSkip + rightSkip;
// Skipping this node lets each child take its better option
int skipHere = Math.Max(leftRob, leftSkip) + Math.Max(rightRob, rightSkip);
return (robHere, skipHere);
}
}Common mistakes
- Returning only one number from the recursive call, such as
max(rob, skip). The parent cannot tell whether the child was robbed, so it cannot enforce the no-adjacent rule. Return the pair. - Writing
node.val + left[0] + right[0]for the robbed case. A robbed node forces its children to be skipped, so the code must addleft[1]andright[1]. - Writing
max(left[0], left[1])only once, or addingleft[0]for the skipped case. Each child must take the better of its two options in the skipped case. - Reading
root.left.leftwhenroot.leftis null in the brute force. Check the child before reading its children, or the code crashes on leaves. - Recursing 10^4 levels deep in Python on a chain-shaped tree. The default limit of 1000 raises a RecursionError, so use the iterative order shown above or raise the limit.
Edge cases
- A single node, for example root = [5]. The answer is 5, because one house can always be robbed.
- A root with one child, for example root = [10, 1]. The answer is 10, because robbing the root alone beats robbing the child.
- All values equal to 0. The answer is 0, and the code must not return a negative or garbage value.
- A chain of 10^4 nodes, where each node has only a left child. The answer comes from alternating choices, and Python needs the iterative version to avoid recursion limits.
- A perfect tree where every node is 10^4. The answer is 10^4 times the number of levels that can be chosen without adjacency, which stays below 10^8 and fits in an int.
Follow-ups interviewers ask
- What if the tree is an N-ary tree, where each node can have any number of children?
- Each node still returns a pair. The rob value is node.val plus the sum of every child's skip value. The skip value is the sum of max(child rob, child skip) over all children. The work per node is proportional to its number of children, so the total stays O(n).
- Can you use O(1) extra space?
- Not with this method. Each ancestor on the current path must hold its partial result until its children finish, so the space is the height H. Morris-style threading can remove the stack for some traversal orders, but it changes the tree and is not the standard answer for this problem. I would state O(H) and explain why.
- What if the tree is too large to fit in memory and arrives as a stream of nodes in postorder?
- Process each node when its event arrives. Keep one pair for each open ancestor, which is the stack of partial results. Memory then depends on the depth H, not on the total number of nodes.
House Robber III FAQ
What is the time complexity of House Robber III?
The optimal postorder solution runs in O(n) time, where n is the number of nodes. Each node is handled once with constant work. The brute force recursion is exponential and times out on deep trees.
Why use postorder DFS for House Robber III?
A parent's decision depends on whether each child was robbed or skipped. Postorder visits children before their parent, so the child pairs are ready when the parent needs them. That order is the core of the Tree DFS pattern here.
Can House Robber III be solved in O(1) extra space?
No, not with the standard method. The recursion or the explicit stack holds one entry for each ancestor on the current path, so the extra space is O(H). Morris traversal can reduce stack use for some orders, but it modifies the tree and is not the usual answer here.
Why not use BFS and sum alternating levels?
Level sums treat every pair of nodes on different levels as conflicting, which is wrong. The rule only blocks a parent and its direct children. Two nodes on adjacent levels can both be robbed if they are not linked, so level sums can give a smaller answer.
Does Python have a recursion gotcha on this problem?
Yes. A chain of 10^4 nodes needs about 10^4 nested calls, and Python's default limit is 1000. The verified Python solution uses an iterative order to avoid this limit.
Asked at
See which companies ask this — Pro
Related problems
- House Robber · same technique: Recursive Postorder Traversal
- Decode Ways · same technique: Recursive Postorder Traversal
- House Robber II · same technique: Recursive Postorder Traversal
- Integer Break · same technique: Recursive Postorder Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Coin Change · same pattern: Tree Traversal Patterns (DFS & BFS)
- Maximum Subarray · same pattern: Tree Traversal Patterns (DFS & BFS)
- Word Break · same pattern: Tree Traversal Patterns (DFS & BFS)
- Longest Increasing Subsequence · same pattern: Tree Traversal Patterns (DFS & BFS)
- Edit Distance · same pattern: Tree Traversal Patterns (DFS & BFS)