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))

你可能感兴趣的:(渣渣要提高编程能力,leetcode,c语言)