House Robber III
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1 3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1 public class Solution {
public int rob(TreeNode root) {
if (root == null) return 0;
// 表示root的parent未被抢
int ret = dfs(root, false);
return ret;
}
// robbed表示其parent是否被抢,如果false,则两个方向,抢或者不抢,选多的返回
// 如果true,则两个不抢,选多的返回
private int dfs(TreeNode root, boolean robbed) {
if (root == null) return 0;
if (robbed) {
// 如果父母被抢,则不抢这个,直接返回两个孩子的和
int left = dfs(root.left, false);
int right = dfs(root.right, false);
return left + right;
} else {
// 如果父母没有被抢,则分情况考虑左右
int left_case1 = dfs(root.left, false);
int left_case2 = dfs(root.left, true);
int right_case1 = dfs(root.right, false);
int right_case2 = dfs(root.right, true);
return Math.max(left_case1 + right_case1, left_case2 + right_case2 + root.val);
}
}
} 3
/ \
4 5
/ \ \
1 3 1 // with memoization
public class Solution {
public int rob(TreeNode root) {
if (root == null) return 0;
// 表示root的parent未被抢
int ret = dfs(root, new HashMap<TreeNode, Integer[]>(), false);
return ret;
}
// robbed表示其parent是否被抢,如果false,则两个方向,抢或者不抢,选多的返回
// 如果true,则两个不抢,选多的返回
// table [0] 存储 robbed, [1] 存parent未抢的情况
private int dfs(TreeNode root, Map<TreeNode, Integer[]> table, boolean robbed) {
if (root == null) return 0;
if (! table.containsKey(root)) table.put(root, new Integer[2]);
if (robbed) {
if (table.get(root)[0] != null) return table.get(root)[0];
// 如果父母被抢,则不抢这个,直接返回两个孩子的和
int left = dfs(root.left, table, false);
int right = dfs(root.right, table, false);
table.get(root)[0] = left + right;
return table.get(root)[0];
} else {
// 如果父母没有被抢,则分情况考虑左右
if (table.get(root)[1] != null) return table.get(root)[1];
int left_case1 = dfs(root.left, table, false);
int left_case2 = dfs(root.left, table, true);
int right_case1 = dfs(root.right, table, false);
int right_case2 = dfs(root.right, table, true);
int ret = Math.max(left_case1 + right_case1, left_case2 + right_case2 + root.val);
table.get(root)[1] = ret;
return ret;
}
}
}