打家劫舍3

class Solution {

public:

pair<int,int> dfs(TreeNode* root) {

if(!root)return {0,0} ;

pair<int,int> l=dfs(root->left);

pair<int,int> r=dfs(root->right);

int choose=root->val+l.second+r.second;//如果选这个节点,那么他的子节点都不能选

int nochoose=max(l.first,l.second)+max( r.first,r.second);//如果不选,取子节点选与不选时得到的最大值

return {choose,nochoose};

}

int rob(TreeNode* root) {

pair<int,int>res=dfs(root);

return max(res.first,res.second);

}

};

相关推荐
故事和你911 天前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__1 天前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__1 天前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程1 天前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程1 天前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒1 天前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣1 天前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮1 天前
Opus 4.7 来了,我并不建议你升级
算法
无敌昊哥战神1 天前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__1 天前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode