您的位置:首页 > 编程语言 > C语言/C++

House Robber III

2016-06-14 16:07 441 查看

c++

/**
* 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) {
//left->right->root
if (root == nullptr) return 0;
int we_rob = 0, we_not_rob = 0;
tryRob(root, we_rob, we_not_rob);
return max(we_rob, we_not_rob);
}
private:
void tryRob(const TreeNode* root, int& we_rob, int& we_not_rob) {
if (root->left == nullptr && root->right == nullptr) {
we_rob = root->val;
we_not_rob = 0;
return;
}
int cur_rob_left = 0;
int cur_not_rob_left = 0;
int cur_rob_right = 0;
int cur_not_rob_right = 0;
if(root->left)
tryRob(root->left,  cur_rob_left,  cur_not_rob_left);
if(root->right)
tryRob(root->right, cur_rob_right, cur_not_rob_right);
we_rob = cur_not_rob_left + cur_not_rob_right + root->val;
int tmp1 = max(cur_rob_left + cur_rob_right, cur_not_rob_left + cur_not_rob_right);
int tmp2 = max(cur_not_rob_left + cur_rob_right, cur_rob_left + cur_not_rob_right);
we_not_rob = max(tmp1, tmp2);
}
};


python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
we_rob, we_not_rob = self.tryRob(root)
return max(we_rob, we_not_rob)

def tryRob(self, root):
if not root.left and not root.right:
return root.val, 0
cur_rob_left,  cur_not_rob_left = 0, 0
cur_rob_right, cur_not_rob_right = 0, 0

if root.left:
cur_rob_left,  cur_not_rob_left = self.tryRob(root.left)
if root.right:
cur_rob_right, cur_not_rob_right = self.tryRob(root.right)

we_rob = cur_not_rob_left + cur_not_rob_right + root.val
we_not_rob = max(cur_rob_left + cur_rob_right,
cur_not_rob_left + cur_not_rob_right,
cur_not_rob_left + cur_rob_right,
cur_rob_left + cur_not_rob_right)
return we_rob, we_not_rob


reference:

http://baike.baidu.com/view/1490835.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言