House Robber III

本文提供了一种使用C++和Python解决二叉树节点中选择性抢劫问题的方法。通过递归算法,计算出抢劫或不抢劫当前节点所能获得的最大价值,最终给出最优解。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值