题目:
小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root 。
除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。
给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。
示例 1:
输入: root = [3,2,3,null,3,null,1]
输出: 7
解释: 小偷一晚能够盗取的最高金额 3 + 3 + 1 = 7
示例2:
输入: root = [3,4,5,1,3,null,1]
输出: 9
解释: 小偷一晚能够盗取的最高金额 4 + 5 = 9
代码:
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob(TreeNode root) {
// if(root == null){
// return 0;
// }
// if(root.left == null && root.right == null){
// return root.val;
// }
// int val1 = root.val;
// //考虑父节点
// if(root.left != null){
// val1 += rob(root.left.left) + rob(root.left.right);
// }
// if(root.right != null){
// val1 += rob(root.right.left) + rob(root.right.right);
// }
// //不考虑父节点
// int val2 = rob(root.left) + rob(root.right);
// return Math.max(val1, val2);
Map<TreeNode, Integer> map = new HashMap<>();
return roll(root, map);
}
public int roll(TreeNode root, Map<TreeNode, Integer> map){
if(root == null){
return 0;
}
if(root.left == null && root.right == null){
return root.val;
}
if(map.containsKey(root)){
return map.get(root);
}
int val1 = root.val;
if(root.left != null){
val1 += roll(root.left.left, map) + roll(root.left.right, map);
}
if(root.right != null){
val1 += roll(root.right.left, map) + roll(root.right.right, map);
}
int val2 = roll(root.left, map) + roll(root.right, map);
int res = Math.max(val1, val2);
map.put(root, res);
return res;
}
}
动态规划
参考别人代码
class Solution {
public int rob(TreeNode root) {
int[] res = roll(root);
return Math.max(res[0], res[1]);
}
public int[] roll(TreeNode root){
int[] res = new int[2];
if(root == null){
return res;
}
int[] left = roll(root.left);
int[] right = roll(root.right);
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = root.val + left[0] + right[0];
return res;
}
}