leetcode 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.

此题即是一个dfs,比较直接的想法,我用c++和java各写了一次,把代码贴过来,比较简单的想法,不做多余解释了

c++:

ass Solution {
public:
    struct Money {
        int p;  
        int c; 
        Money():p(0), c(0){}
    };
 
    int rob(TreeNode* root) {
        Money sum = dfs(root);
        return sum.c;
    }
 
    Money dfs(TreeNode* root)
    {
        if (root == NULL) return Money();
        Money leftMoney = dfs(root->left);   
        Money rightMoney = dfs(root->right); 
        Money sumMoney;
        sumMoney.p = leftMoney.c + rightMoney.c; 
        sumMoney.c = max(sumMoney.p, root->val + leftMoney.p + rightMoney.p);
        return sumMoney;
    }
};

java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    

    class Money {
        int p = 0;
        int c = 0;
    }
    
    static int max(int a,int b){
        if(a > b){
            return a;
        }else{
            return b;
        }
    }
    int rob(TreeNode root) {
        Money sum = dfs(root);
        return sum.c;
    }
 
    Money dfs(TreeNode root)
    {
        if (root == null) {
        Money money = new Money();
        return money;
        }
        Money leftMoney = dfs(root.left);   
        Money rightMoney = dfs(root.right); 
        Money sumMoney = new Money();
        sumMoney.p = leftMoney.c + rightMoney.c; 
        sumMoney.c = max(sumMoney.p, root.val + leftMoney.p + rightMoney.p);
        return sumMoney;
    }
}

 

posted on 2016-04-12 15:12  没结果的花  阅读(175)  评论(0编辑  收藏  举报

导航