LeetCode-House Robber III

LiBlog發表於2016-08-02

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.

Analysis:

Two states at each root: rob root, not rob root.

Solution:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public class RobResult {
12         int robProfit;
13         int noRobProfit;
14         public RobResult(int rp, int nrp){
15             robProfit = rp;
16             noRobProfit = nrp;
17         }
18     }
19     
20     public int rob(TreeNode root) {
21         RobResult res = robRecur(root);
22         return Math.max(res.robProfit,res.noRobProfit);        
23     }
24 
25     public RobResult robRecur(TreeNode cur){
26         if (cur==null){
27             return new RobResult(0,0);
28         }
29 
30         RobResult leftRes = robRecur(cur.left);
31         RobResult rightRes = robRecur(cur.right);
32 
33         RobResult curRes = new RobResult(leftRes.noRobProfit+rightRes.noRobProfit+cur.val, Math.max(leftRes.noRobProfit,leftRes.robProfit)+Math.max(rightRes.noRobProfit,rightRes.robProfit));
34         return curRes;
35     }
36 }

 

相關文章