337. 打家劫舍 III

二叉树+动态规划就不会了,把代码保存一下

查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rob(TreeNode* root) {
        if(root == nullptr){
            return 0;
        }
        int result = 0;
        result = rob_max(root,0);
        return result;
    }
    int rob_max(TreeNode* root,int flag){
        if(root == nullptr){
            return 0;
        }
        int result = 0;
        if(flag == 0){
                result += max(rob_max(root->left,0)+rob_max(root->right,0),rob_max(root->left,1)+rob_max(root->left,1)+root->val);
                int result_1 = max(rob_max(root->left,1)+rob_max(root->right,0),rob_max(root->left,0)+rob_max(root->right,1));
                result = max(result,result_1);
    }
         else{
             result += rob_max(root->left,0)+rob_max(root->right,0);
         }
        return result;
    }
};

官方代码,使用了结构就好样的,函数返回结构体还能这么返回,解决了一个大问题,这可能才是我觉得二叉树+动态规划的难点

不知道怎么返回两个变量,然后后序遍历处理。

查看代码
struct SubtreeStatus {
    int selected;
    int notSelected;
};

class Solution {
public:
    SubtreeStatus dfs(TreeNode* node) {
        if (!node) {
            return {0, 0};
        }
        auto l = dfs(node->left);
        auto r = dfs(node->right);
        int selected = node->val + l.notSelected + r.notSelected;
        int notSelected = max(l.selected, l.notSelected) + max(r.selected, r.notSelected);
        return {selected, notSelected};
    }

    int rob(TreeNode* root) {
        auto rootStatus = dfs(root);
        return max(rootStatus.selected, rootStatus.notSelected);
    }
};

 

posted @ 2021-12-27 21:34  jozon  阅读(38)  评论(0)    收藏  举报