House Robber III

Medium

Topics
TreeDFSDynamic Programming

Houses are arranged as a binary tree. You cannot rob two directly-connected houses (a parent and its child) on the same night. Given the root, return the maximum amount of money you can rob without alerting the police.

Example 1

23331
robbed
No two shaded nodes are parent and child, and they total 7. Each node returns two numbers — best if it is robbed, best if it is not — because a parent’s choice depends on which of those its children took.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [3,2,3,null,3,null,1]
Output: 7

Example 2

143351
robbed
Input:  root = [3,4,5,1,3,null,1]
Output: 9

Constraints

  • 1 <= number of nodes <= 10^4
  • 0 <= Node.val <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

The constraint is that no two directly connected houses may both be robbed. On a line this is the classic two-state DP; on a tree it is the same idea, with the states returned up the recursion.

The wrong framing is to compute a single "best from this subtree" number, because that loses the information a parent needs: whether the child's best plan used the child itself. If it did, the parent cannot also be robbed.

So each node returns a pair:

  • take — the best total for this subtree with this node robbed, which forces both children to be skipped: node.val + left.skip + right.skip
  • skip — the best with this node not robbed, which frees each child to do whatever is better for it: max(left) + max(right)

The asymmetry is the whole point. take must use the children's skip values specifically, while skip may use either of theirs — and that is exactly the adjacency rule expressed arithmetically.

Approach

  1. Post-order DFS returning (take, skip); null returns (0, 0).
  2. Combine as above.
  3. Answer is max of the root's pair.

Dry Run

tree       3
          / \
         2   3
          \    \
           3    1

leaf 3 (left's child):  take 3, skip 0
node 2:   take = 2 + 0        = 2
          skip = max(3,0)     = 3        -> (2, 3)
leaf 1:   take 1, skip 0
node 3 (right): take = 3 + 0  = 3
                skip = max(1,0) = 1      -> (3, 1)
root 3:   take = 3 + 2.skip + 3.skip = 3 + 3 + 1 = 7
          skip = max(2,3) + max(3,1)     = 3 + 3 = 6

answer max(7, 6) = 7   (rob the root and both grandchildren)

Note the root's take uses 3 and 1 — the children's skip values — not their maxima of 3 and 3. Using the maxima there would double-count a robbed child.

Complexity

  • Time — O(n): each node visited once, constant work per node. A naive recursion that recomputes grandchildren is exponential, which is why the pair must be returned rather than recomputed.
  • Space — O(h): the recursion stack.

Common Pitfalls

  • Returning one number instead of a pair. The parent cannot then tell whether the child was robbed, and the adjacency rule becomes unenforceable.
  • Using max(child) in the take branch. It must be the child's skip specifically.
  • Writing the naive recursion that calls down to grandchildren directly. Correct, exponential, and the reason memoisation or the pair is needed.
  • Returning take from the root rather than the maximum of the pair.
  • Assuming the tree is binary-search ordered or balanced. Neither is promised, and neither matters.

Full Solution — all languages

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):
        def dfs(node):
            if not node: return (0, 0)
            l = dfs(node.left); r = dfs(node.right)
            take = node.val + l[1] + r[1]
            skip = max(l) + max(r)
            return (take, skip)
        return max(dfs(root))
Asked at Sprinklr Two Sigma
SensAI
Beta
Tap the mic to stop voice mode