House Robber III
Medium
Topics
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
null marks a missing child.Input: root = [3,2,3,null,3,null,1] Output: 7
Example 2
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.skipskip— 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
- Post-order DFS returning
(take, skip); null returns(0, 0). - Combine as above.
- Answer is
maxof 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 thetakebranch. It must be the child'sskipspecifically. - Writing the naive recursion that calls down to grandchildren directly. Correct, exponential, and the reason memoisation or the pair is needed.
- Returning
takefrom 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))import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int rob(TreeNode root) {
int[] res = dfs(root);
return Math.max(res[0], res[1]);
}
private int[] dfs(TreeNode node) {
if (node == null) return new int[]{0, 0};
int[] l = dfs(node.left), r = dfs(node.right);
int take = node.val + l[1] + r[1];
int skip = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
return new int[]{take, skip};
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int rob(TreeNode* root) {
function<pair<int,int>(TreeNode*)> dfs = [&](TreeNode* node) -> pair<int,int> {
if (!node) return {
0, 0
};
auto l = dfs(node->left);
auto r = dfs(node->right);
int take = node->val + l.second + r.second;
int skip = max(l.first, l.second) + max(r.first, r.second);
return {
take, skip
};
};
auto res = dfs(root);
return max(res.first, res.second);
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var rob = function(root) {
const dfs = (node) => {
if (!node) return [0, 0];
const l = dfs(node.left), r = dfs(node.right);
const take = node.val + l[1] + r[1];
const skip = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
return [take, skip];
};
const res = dfs(root);
return Math.max(res[0], res[1]);
};