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.

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


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

而且隔行的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:

![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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容