House Robber III
ID:337
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.Idea
Code
Last updated
ID:337
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.Last updated
public int rob(TreeNode root) {
return rob(root, new HashMap<>());
}
public int rob(TreeNode root, Map<TreeNode, Integer> map) {
if (root == null) return 0;
if (map.containsKey(root)) return map.get(root);
int ans = 0;
if (root.left != null) {
ans += rob(root.left.left, map) + rob(root.left.right, map);
}
if (root.right != null) {
ans += rob(root.right.left, map) + rob(root.right.right, map);
}
ans = Math.max(ans + root.val, rob(root.left, map) + rob(root.right, map));
map.put(root, ans);
return ans;
}