文章
99
粉丝
120
获赞
8
访问
110.1k
/**
* 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 {
public:
//f[i],选第i个点能获得的最大价值
//g[i],不选第i个点能获得的最大价值
unordered_map<TreeNode*, int> f, g;
void dfs(TreeNode* u){
if(!u)return ;
dfs(u->left);
dfs(u->right);
f[u] = u->val+g[u->left]+g[u->right];
g[u] = max(f[u->left],g[u->left])+max(f[u->right],g[u->right]);
}
int rob(TreeNode* root) {
dfs(root);
return max(f[root], g[root]);
}
};
登录后发布评论
暂无评论,来抢沙发