Skip to content
Problem 337 · LeetCode 337(opens in a new tab)

House Robber III

MediumDepth-first search

The houses in a neighbourhood are laid out as a binary tree: root is the first house, and every other house hangs off exactly one parent house. Each node's value is the money inside that house.

A thief may rob any houses, except that robbing two houses joined directly by an edge (a parent and its child) sets off the alarm. Return the most money the thief can take without setting it off.

Example 1

Input:  root = [5, 1, 6, null, 3, 2]
Output: 10
Why:    rob 5, 3 and 2; none of them is a parent of another
2 more examples and the constraints

Example 2

Input:  root = [2, 1, 3, null, 4]
Output: 7
Why:    rob 3 and 4; they sit on different levels but are not linked

Example 3

Input:  root = [7]
Output: 7
Why:    a single house is safe to rob

Constraints

  • The tree has between 1 and 10,000 nodes
  • 0 ≤ value of a node ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursion with a memoO(n)
  2. Return (rob, skip) pairsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
Recursion with a memoO(n)
Passes; up to 7 calls and a map lookup per node
Return (rob, skip) pairsO(n)
Best; one visit per node, no map

n = number of nodes, h = height of the tree.

Edge cases to test

  • One node. Rob it: the answer is its value.
  • A chain. A tree with one child per node is House Robber on a line; the best may skip two in a row.
  • Zero-value houses. All zeros give 0, and a zero node is as good robbed as skipped.
  • Root not robbed. In [1, 9, 9] the best is 18, taking both children and leaving the root.

Common mistakes

  • Assuming the answer alternates by level (sum of even levels or odd levels); in Example 2 the best mixes levels.
  • Making a skipped node force its children to be robbed, instead of letting each child choose.
  • Running plain recursion over children and grandchildren without a memo, which blows up on deep trees.

How to talk through it

  1. 1Clarify. Only parent and child are forbidden, not siblings? Can values be 0?
  2. 2State the choice. Rob a node and use its grandchildren, or skip it and use its children.
  3. 3Fix the repeats. Memoise by node, or better, return a (rob, skip) pair from each call.
  4. 4Code the pair version. Post-order: get both children's pairs, then combine.
  5. 5Test out loud. Run one node, a chain, and a root that should be skipped.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?