House Robber III

Tree-shaped house arrangement — return max loot using DP returning (rob-root, skip-root) per node.

Medium
Time O(n) Space O(h)
LeetCode
3 min read
backtracking tree dp

Problem#

Houses arranged in a binary tree. Adjacent (parent-child) houses can’t both be robbed. Return the maximum total loot.

Examples#

  • [3,2,3,null,3,null,1]7

Constraints#

  • 1 <= n <= 10^4.

Approach#

Post-order DFS returning a pair (rob, skip) per subtree. rob = val + leftSkip + rightSkip; skip = max(leftRob, leftSkip) + max(rightRob, rightSkip). Answer is max of the root’s pair.

Solution#

House Robber III
class Solution {
public:
int rob(TreeNode* root) {
auto [a, b] = dfs(root);
return max(a, b);
}
private:
pair<int,int> dfs(TreeNode* n) {
if (!n) return {0, 0};
auto [lRob, lSkip] = dfs(n->left);
auto [rRob, rSkip] = dfs(n->right);
int rob = n->val + lSkip + rSkip;
int skip = max(lRob, lSkip) + max(rRob, rSkip);
return {rob, skip};
}
};

Editorial#

Returning two values per call avoids recomputation. The DP recurrence is “either rob this node (forbid children) or skip it (children free to do either)” — same structure as the linear House Robber but on a tree.

Complexity#

  • Time: O(n).
  • Space: O(h) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.