House Robber III

来源:互联网 发布:上瘾网络剧英文插曲 编辑:程序博客网 时间:2024/05/31 13:14

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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

思路:跟Largest BST思路一样,都是buttom up,从下面往上传递信息,每个node往上传的信息有两个,偷本身的最大值和不偷本身的最大值。

那么 Tou(3) = 3.val + notTou(4) + notTou(5)

notTou (3) = Max(Tou(4) + Tou(5),   notTou(4) + Tou(5),  Tou(4) + notTou(5) ) 三者的最大值,

综合一下就是 notTou(3) = Math.max( Tou(4), notTou(4)) + Math.max(notTou(5) , Tou(5));

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int rob(TreeNode root) {        if(root == null) return 0;        int[] res = {0};        collect(root, res);        return res[0];    }        public Node collect(TreeNode root, int[] res){        Node node = new Node();        if(root == null){            return node;        }                Node leftnode = collect(root.left, res);        Node rightnode = collect(root.right, res);        node.inmax = root.val + leftnode.noinmax + rightnode.noinmax;        node.noinmax = Math.max(leftnode.inmax, leftnode.noinmax) + Math.max(rightnode.noinmax, rightnode.inmax);        res[0] = Math.max(res[0], Math.max(node.inmax, node.noinmax));        return node;    }        class Node{        public int inmax;        public int noinmax;        public Node() {            inmax = 0;            noinmax = 0;        }    }}

思路2: 用array来传参,代码更简洁;array[0] 代表偷,array[1] 代表不偷。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int rob(TreeNode root) {        if(root == null) return 0;        int[] res = collect(root);        return Math.max(res[0],res[1]);    }        public int[] collect(TreeNode root){        if(root == null) return new int[2];        int[] left = collect(root.left);        int[] right = collect(root.right);        int[] res = new int[2];        res[0] = root.val + left[1] + right[1];        res[1] = Math.max(left[0],left[1]) + Math.max(right[0], right[1]);        return res;    }}


0 0
原创粉丝点击