1.题目
LeetCode: 337. 打家劫舍 III
【medium】
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
输出: 7
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
示例 2:
输入: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
2.解题
方法一:递归法
由于不能偷相邻节点,所以如果偷当前节点,那么他的儿子节点就不能偷,孙子节点可以偷,所以一个节点最多有两个儿子节点和四个孙子节点,我们只要比较当前节点的值和四个孙子节点的值的和与两个儿子节点的值的和的大小即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
if (root == null) return 0;
int max1 = root.val;
if (root.left != null) max1 += rob(root.left.left) + rob(root.left.right);
if (root.right != null) max1 += rob(root.right.left) + rob(root.right.right);
int max2 = rob(root.left) + rob(root.right);
return max1 > max2 ? max1 : max2;
}
}
方法二:递归+数组
参考:
https://leetcode-cn.com/problems/house-robber-iii/solution/san-chong-fang-fa-jie-jue-shu-xing-dong-tai-gui-hu/
java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
if (root == null) return 0;
int[] res = rob2(root);
return Math.max(res[0], res[1]);
}
public int[] rob2(TreeNode root) {
if (root == null) return new int[2];
int[] res = new int[2];
int[] left = rob2(root.left);
int[] right = rob2(root.right);
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = left[0] + right[0] + root.val;
return res;
}
}