Community Problem

House Robber III

Difficulty: Medium

Maximize money robbed from a binary-tree neighborhood where no two directly-connected houses can both be robbed.

House Robber III

Maximize money robbed from a binary-tree neighborhood where no two directly-connected houses can both be robbed.

MEDIUM
Free
trees
binary-tree
dfs
recursion
milozhang

By @milozhang

May 16, 2026

·

Updated May 20, 2026

869 views

7

4.3 (12)

I love this one as a follow-up after candidates solve the original House Robber on a line, because it forces them to translate "max independent set on a path" into "max independent set on a tree". The tree version is the cleanest example of post-order DP I know: every recursive call returns a tuple of two values (rob this node, skip this node), and the parent combines them. The catalog has linear House Robber but skipped this generalization.

House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were 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.

Examples

Example 1:

  • Input: root = [3, 2, 3, null, 3, null, 1]
  • Output: 7
  • Explanation: Rob the root (3) plus the two leaf grandchildren (3 and 1). Total 3 + 3 + 1 = 7. Robbing any direct child would forbid robbing the root and cap the total below 7.

Example 2:

  • Input: root = [3, 4, 5, 1, 3, null, 1]
  • Output: 9
  • Explanation: Rob the two children of the root (4 + 5 = 9). Robbing the root would forbid robbing either child, capping the total at 3 + 1 + 3 + 1 = 8.

Example 3:

  • Input: root = [1]
  • Output: 1
  • Explanation: Single house, no neighbors to worry about.

Example 4:

  • Input: root = [10, 1, 1, null, null, 1, 1]
  • Output: 12
  • Explanation: Rob the root (10) plus the two grandchildren (1 + 1). Total 12.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • 0 <= Node.val <= 10^4.

Follow-up

The naive recursion that calls rob(grandchildren) and rob(child) is exponential. The post-order tuple version is O(n). Can you explain why each subtree is visited exactly once in the tuple version?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems