方法一:
class Solution {
public int rob(TreeNode root) {
Map<TreeNode, Integer> map = new HashMap<>();
return robInterval(root, map);
}
public int robInterval(TreeNode root, Map<TreeNode, Integer> map) {
if (root == null) {
return 0;
}
if (map.get(root) != null) {
return map.get(root);
}
int money = root.val;
if (root.left != null) {
money = money + robInterval(root.left.left, map) + robInterval(root.left.right, map);
}
if (root.right != null) {
money = money + robInterval(root.right.left, map) + robInterval(root.right.right, map);
}
int maxVal = Math.max(money, robInterval(root.left, map) + robInterval(root.right, map));
map.put(root, maxVal);
return maxVal;
}
}
方法二:
// 优化版
class Solution {
public int rob(TreeNode root) {
// 0不抢劫,1抢劫
int[] result = robInternal(root);
return Math.max(result[0], result[1]);
}
public int[] robInternal(TreeNode root) {
if (root == null) {
return new int[2];
}
int[] leftVal = robInternal(root.left);
int[] rightVal = robInternal(root.right);
int[] result = new int[2];
result[0] = Math.max(leftVal[0], leftVal[1]) + Math.max(rightVal[0], rightVal[1]);
result[1] = root.val + leftVal[0] + rightVal[0];
return result;
}
}