跳转至

打家劫舍 III⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

/**
 * 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 {
private:
    unordered_map<TreeNode*, int> memo;
public:
    int rob(TreeNode* root) {
        if (!root) return 0;
        if (memo.count(root)) return memo[root];

        int do_rob = root->val + ((root->left) ? (rob(root->left->left) + rob(root->left->right)) : 0) + ((root->right) ? (rob(root->right->left) + rob(root->right->right)) : 0);
        int go_next = rob(root->left) + rob(root->right);

        int res = max(do_rob, go_next);
        memo[root] = res;
        return res;
    }
};