The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “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 forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 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
Maximum amount of money the thief can rob = 4 + 5 = 9.
解法一:带hashmap优化的递归:
HashMap<TreeNode,Integer> map = new HashMap<>();
public int rob(TreeNode root) {
if (root == null) return 0;
if (map.containsKey(root)) return map.get(root);
int val = root.val;
if (root.left != null) {
val += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
val += rob(root.right.left) + rob(root.right.right);
}
int result = Math.max(val, rob(root.left) + rob(root.right));
map.put(root, result);
return result;
}
解法二:时间复杂度最优的解法,dp,每次返回一个大小为2的数组,int[0]代表此节点rob的最大值,int[1]代表此节点不rob的最大值。
public int rob(TreeNode root) {
if (root == null) return 0;
int[] result = helper(root);
return Math.max(result[0], result[1]);
}
public int[] helper(TreeNode root) {
if (root == null) return new int[2];
int[] result = new int[2];
int[] res = helper(root.left);
int[] res2 = helper(root.right);
result[0] = root.val + res[1] + res2[1];
result[1] = Math.max(res[0], res[1]) + Math.max(res2[0], res2[1]);
return result;
}