问题
例子
思路
对于根节点root,
偷它时,则不能再偷子结点,只能偷孙子结点
如果不偷,可偷子结点
比较两种方式哪种偷的多
-
方法1
$$$$
直接递归
-
方法2
$$$$
由于有大量的重复计算,所以保存计算的结果
代码
//方法1
public int rob(TreeNode root) {
if(root==null) return 0;
//抢该层,就不能抢下一层,要抢下下层
int a1 = root.left==null?0:rob(root.left.left)+rob(root.left.right);
int a2 = root.right==null?0:rob(root.right.left)+rob(root.right.right);
int a = root.val+a1+a2;
//不抢该层,就抢下一层
int b = rob(root.left)+rob(root.right);
return Math.max(a,b);
}
//方法2
class Solution {
public int rob(TreeNode root) {
Map<TreeNode, Integer> map = new HashMap<>();
return get(root,map);
}
public int get(TreeNode root, Map<TreeNode,Integer> map) {
if(root==null) return 0;
if(map.containsKey(root)) return map.get(root);
//抢该层,就不能抢下一层,要抢下下层
int a1 = root.left==null?0:get(root.left.left,map)+get(root.left.right,map);
int a2 = root.right==null?0:get(root.right.left,map)+get(root.right.right,map);
int a = root.val+a1+a2;
//不抢该层,就抢下一层
int b = get(root.left,map)+get(root.right,map);
int res = Math.max(a,b);
map.put(root,res);
return res;
}
}