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.
這道題我一開(kāi)始的思路有問(wèn)題,我簡(jiǎn)單地以為就是隔一層地取,相當(dāng)于隔層進(jìn)行BFS, 但是實(shí)際上有反例證明可以不是隔行取的。比如:

而且隔行的BFS也完全沒(méi)有遇到過(guò),也不會(huì)具體實(shí)施。
后來(lái)看了答案,發(fā)現(xiàn)作者用的遞歸方法很巧妙。作者的helper method返回的是一個(gè)int[2]的數(shù)組,其中res[0]表示當(dāng)前節(jié)點(diǎn)被偷取所能取得的最大金額;res[1]表示的是當(dāng)前節(jié)點(diǎn)不被偷所能取得的最大金額。當(dāng)前節(jié)點(diǎn)被偷的時(shí)候,其左右節(jié)點(diǎn)不能被偷,所以當(dāng)前節(jié)點(diǎn)被偷的時(shí)候最大金額就是res[0] = root.val + left[1] + right[1]; 而當(dāng)前節(jié)點(diǎn)不被偷的時(shí)候, 不一定它的左子樹(shù)和右子樹(shù)就會(huì)被偷,這也是最容易錯(cuò)的地方。就比如[4,2,null,1,null,3]這個(gè)樹(shù),最大值是4 + 3 = 7 而不是 4 + 1 = 5. 所以這時(shí)候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;
}
}