思路: left[0] 是抢劫这个节点的最大值。1 是不包含这个节点的最大值。
代码1:
int rob(TreeNode* root) {
vector<int> res=dfs(root);
return max(res[0],res[1]);
}
vector<int> dfs(TreeNode* root){
vector<int> res(2);
if(root==NULL)
return res;
vector<int> left=dfs(root->left);
vector<int> right=dfs(root->right);
res[1]=max(left[0],left[1])+max(right[0],right[1]);
res[0]=root->val+left[1]+right[1];
return res;
}
代码2:
int rob(TreeNode* root) {
if(root==NULL)
return 0;
int sum=0;
if(root->left){
sum += rob(root->left->left)+rob(root->left->right);
}
if(root->right){
sum += rob(root->right->left)+rob(root->right->right);
}
return max(root->val+sum,rob(root->left)+rob(root->right));
}