lintcode:打劫房屋 III

题目

打劫房屋 III

在上次打劫完一条街道之后和一圈房屋之后,窃贼又发现了一个新的可以打劫的地方,但这次所有的房子组成的区域比较奇怪,聪明的窃贼考察地形之后,发现这次的地形是一颗二叉树。与前两次偷窃相似的是每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且当相邻的两个房子同一天被打劫时,该系统会自动报警

算一算,如果今晚去打劫,你最多可以得到多少钱,当然在不触动报警装置的情况下。

样例

  3
 / 
2   3
     
  3   1

窃贼最多能偷窃的金钱数是 3 + 3 + 1 = 7.

    3
   / 
  4   5
 /     
1   3   1

窃贼最多能偷窃的金钱数是 4 + 5 = 9.

解题

参考链接

后序遍历二叉树,每次遍历返回两个值:分别表示偷窃或者不偷窃当前节点可以获得的最大收益。

程序

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: The maximum amount of money you can rob tonight
     */
    public int houseRobber3(TreeNode root) {
        // write your code here
        int[] result = postTraver(root);
        return Math.max(result[0], result[1]);
    }

    public int[] postTraver(TreeNode root) {
        if(root == null) 
            return new int[]{0, 0};
        int[] result = new int[2];
        int[] left = postTraver(root.left);
        int[] right = postTraver(root.right);
        //表示偷
        result[0] = left[1] + right[1] + root.val;
        //表示不偷
        result[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        return result;
        
    }
        
}

博客中讲解:

对当前节点为根节点的树进行讨论,有打劫和不打劫当前节点两种可能。如果打劫,则不能打劫其子节点;否则可以打劫其子节点。则其能获得的最大金钱为打劫和不打劫当前节点两种可能中的最大值。

好像就是这样理解的。。。

原文地址:https://www.cnblogs.com/theskulls/p/5538291.html