15% off all plans & roadmaps Use code

See plans

House Robber III

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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Return 0 when the node is null.
  2. Start rob_here at node.val, then add rob of each grandchild through the left and right children, skipping null children.
  3. Set skip_here to rob(node.left) plus rob(node.right).
  4. Return the larger of rob_here and skip_here.
  5. 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

TimeExponential in n, O(1.618^n) on a chain
SpaceO(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)

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 infographic

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

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

  1. Visit the children before the parent, which is postorder.
  2. For a null child, use the pair (0, 0).
  3. Read each child's pair as (rob, skip).
  4. Set rob_here to node.val + left skip + right skip.
  5. Set skip_here to max(left rob, left skip) + max(right rob, right skip).
  6. Return the pair (rob_here, skip_here) for the node.
  7. 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.

StepNodeLeft pair (rob, skip)Right pair (rob, skip)rob_hereskip_hereStored pair
1C (3)(0, 0)(0, 0)30(3, 0)
2B (2)(0, 0)(3, 0)23(2, 3)
3E (1)(0, 0)(0, 0)10(1, 0)
4D (3)(0, 0)(1, 0)31(3, 1)
5A (3)(2, 3)(3, 1)76(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

TimeO(n)
SpaceO(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])

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 add left[1] and right[1].
  • Writing max(left[0], left[1]) only once, or adding left[0] for the skipped case. Each child must take the better of its two options in the skipped case.
  • Reading root.left.left when root.left is 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

Practise it