337. 打家劫舍 III
class Solution {
public:
vector<int> robInternal(TreeNode* root){
if(root == nullptr){
return vector<int>{0, 0};
}
vector<int> left = robInternal(root->left);
vector<int> right = robInternal(root->right);
int val0 = max(left[0], left[1]) + max(right[0], right[1]);
int val1 = root->val + left[0] + right[0];
return {val0, val1};
}
int rob(TreeNode* root) {
vector<int> result = robInternal(root);
return max(result[0], result[1]);
}
};
class Solution {
public:
int robInternal(TreeNode* root, unordered_map<TreeNode*, int> map_TreeNode_money){
if(root == nullptr){
return 0;
}
if(map_TreeNode_money.count(root)){
return map_TreeNode_money.at(root);
}
int money_root_grandsons = root->val;
if(root->left != nullptr){
money_root_grandsons += (robInternal(root->left->left, map_TreeNode_money) + robInternal(root->left->right, map_TreeNode_money));
}
if(root->right != nullptr){
money_root_grandsons += (robInternal(root->right->left, map_TreeNode_money) + robInternal(root->right->right, map_TreeNode_money));
}
int money_root_sons = robInternal(root->left, map_TreeNode_money) + robInternal(root->right, map_TreeNode_money);
int result = money_root_sons > money_root_grandsons ? money_root_sons : money_root_grandsons;
map_TreeNode_money.insert(make_pair(root, result));
return result;
}
int rob(TreeNode* root) {
unordered_map<TreeNode*, int> map_TreeNode_money;
return robInternal(root, map_TreeNode_money);
}
};
class Solution {
public:
int rob(TreeNode* root) {
if(root == nullptr){
return 0;
}
int money_root_grandsons = root->val;
if(root->left != nullptr){
money_root_grandsons += (rob(root->left->left) + rob(root->left->right));
}
if(root->right != nullptr){
money_root_grandsons += (rob(root->right->left) + rob(root->right->right));
}
int money_root_sons = rob(root->left) + rob(root->right);
return money_root_sons > money_root_grandsons ? money_root_sons : money_root_grandsons;
}
};