337. House Robber III C语言

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.

大概的升级套路就是:线性->⭕️->二叉树
 二叉树肯定就是递归了嘛
首先递归的式子就是:
maxBenifit = max(rob(left) + rob(right), root.val + rob(ll) + rob(lr) + rob(rl) + rob(rr))

大概就是介个样子,相当于每一次都是一个新的开辟,只不过是树的根不一样了,借鉴网上大神的做法,本人C++不熟,那就C呗~


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int rob(struct TreeNode* root)
{   int benefit=0,bene=0;
    if(!root)
        return 0;
   
        if(root->left)
          benefit=rob(root->left->left)+rob(root->left->right);   
            
        if(root->right)
           benefit=benefit+rob(root->right->left)+rob(root->right->right);   
 
         benefit=benefit+root->val;
         bene=rob(root->left)+rob(root->right);  
        
 
        if(bene>benefit)
           return bene;
        else 
          return benefit;
    
}
大概就是benefit记录的是这层加上其子树的孩子的最大值(偷这一层),bene记录的是这层左右子树的值(不偷这一层)
max(rob(left) + rob(right), root.val + rob(ll) + rob(lr) + rob(rl) + rob(rr))
max(rob(left) + rob(right), root.val + rob(ll) + rob(lr) + rob(rl) + rob(rr))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值