337. House Robber III

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, 但是實際上有反例證明可以不是隔行取的。比如:


Screen Shot 2017-10-09 at 3.02.05 PM.png

而且隔行的BFS也完全沒有遇到過,也不會具體實施。

后來看了答案,發(fā)現(xiàn)作者用的遞歸方法很巧妙。作者的helper method返回的是一個int[2]的數(shù)組,其中res[0]表示當前節(jié)點被偷取所能取得的最大金額;res[1]表示的是當前節(jié)點不被偷所能取得的最大金額。當前節(jié)點被偷的時候,其左右節(jié)點不能被偷,所以當前節(jié)點被偷的時候最大金額就是res[0] = root.val + left[1] + right[1]; 而當前節(jié)點不被偷的時候, 不一定它的左子樹和右子樹就會被偷,這也是最容易錯的地方。就比如[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:

![Screen Shot 2017-10-09 at 2.26.51 PM.png](http://upload-images.jianshu.io/upload_images/5350214-13d8915955c6cbb5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Screen Shot 2017-10-09 at 2.26.51 PM.png
/**
 * 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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容