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
.
这道题我一开始的思路有问题,我简单地以为就是隔一层地取,相当于隔层进行BFS, 但是实际上有反例证明可以不是隔行取的。比如:
而且隔行的BFS也完全没有遇到过,也不会具体实施。
后来看了答案,发现作者用的递归方法很巧妙。作者的helper method返回的是一个int[2]的数组,其中res[0]表示当前节点被偷取所能取得的最大金额;res[1]表示的是当前节点不被偷所能取得的最大金额。当前节点被偷的时候,其左右节点不能被偷,所以当前节点被偷的时候最大金额就是res[0] = root.val + left[1] + right[1]; 而当前节点不被偷的时候, 不一定它的左子树和右子树就会被偷,这也是最容易错的地方。就比如[4,2,null,1,null,3]这个树,最大值是4 + 3 = 7 而不是 4 + 1 = 5. 所以这时候res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
submit 1:
/**
* 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) {
int[] res = helper(root);
return Math.max(res[0], res[1]);
}
public int[] helper(TreeNode root){
if (root == null){
int[] res = new int[]{0, 0};
return res;
}
int[] res = new int[2];
int[] left = helper(root.left);
int[] right = helper(root.right);
//res[0] is when root is selected, res[1] is when root is not selected
res[0] = root.val + left[1] + right[1];
res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return res;
}
}