您的位置:首页 > 其它

337. House Robber III

2016-03-27 21:35 176 查看
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.

分析:

下面的代码我觉得很奇妙,抓不住其中的道理,递归的概念还是不够清晰。

对于每一个节点,都可以有两种的结果,1自己+grandnode的vals,2左子树的节点值加右子树的值。

也算动态规划吧,只是做法不同一样。

/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    int tryRob(TreeNode* root, int &l,int &r)

    {

        if(root==NULL) return 0;

        int ll=0,lr=0,rl=0,rr=0;

        l=tryRob(root->left,ll,lr);

        r=tryRob(root->right,rl,rr);

        return max(root->val+ll+lr+rl+rr,l+r);

    }

    int rob(TreeNode* root) {

        int l, r;

        return tryRob(root, l, r);

    }

};

上面解法的精髓在于不会计算两次,因此很不好理解。写了个简单版本的,这个版本比较好理解,但的确计算成本太高,

代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rob(TreeNode* root) {
if(root==NULL){
return 0;
}
if(root->left==NULL&&root->right==NULL){
return root->val;
}
int leftval = 0;
int leftonly = 0;
int rightval = 0;
int rightonly = 0;
if(root->left){
leftval = rob(root->left->left)+rob(root->left->right);
leftonly= rob(root->left);
}
if(root->right){
rightval = rob(root->right->left)+rob(root->right->right);
rightonly= rob(root->right);
}
return max((root->val+leftval+rightval),leftonly+rightonly);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  遍历 tree