class Solution {
#define x first
#define y second
typedef pair<int,int> PII;
public:
int rob(TreeNode* root) {
if(!root) return 0;
auto t =dfs(root);
int ans=max(t.x,t.y);
return ans;
}
inline PII dfs(TreeNode* u){//pair<tou,butou>
if(!u) return {0,0};
int stolen=u->val;
PII l = dfs(u->left);
PII r = dfs(u->right);
stolen +=l.y+r.y ;
int nostolen=0;
if (l.x>l.y) nostolen=l.x;
else nostolen =l.y;
if (r.x>r.y) nostolen +=r.x;
else nostolen +=r.y;
PII t={stolen , nostolen};
return t;
}
};
运行效率:
宏定义与类型别名:
cpp复制代码
#define x first // 用 x 表示 pair 的 first(偷当前节点的最大值)
#define y second // 用 y 表示 pair 的 second(不偷当前节点的最大值)
typedef pair<int, int> PII;
PII 是一个二元组,存储两个状态:
cpp复制代码
first(x):偷当前节点时的最大收益。
second(y):不偷当前节点时的最大收益。
主函数 rob:
若树为空,直接返回0。
调用dfs递归计算根节点的两种状态,返回较大值。
cpp复制代码
int rob(TreeNode* root) {
if (!root) return 0;
auto t = dfs(root);
return max(t.x, t.y); // 最终结果取根节点偷或不偷的最大值
}