方法一:
树上dp,通过两个unordered_map记录每个点选择获取或者不选择获取的状态。
选择则状态转移方程为f[o]=o->val+g[o->left]+g[o->right]
不选择点的状态为g[o]=max(f[o->left],g[o->left])+max(f[o->right],g[o->right])
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<TreeNode*,int>f,g;//f代表选择当前结点,o代表不选择当前节点
void DFS(TreeNode* o)
{
if(!o)return;
DFS(o->left);
DFS(o->right);
f[o]=o->val+g[o->left]+g[o->right];
g[o]=max(f[o->left],g[o->left])+max(f[o->right],g[o->right]);
}
int rob(TreeNode* root) {
DFS(root);
return max(f[root],g[root]);
}
};
方法二:
由于父结点的状态只和子节点有关,所以产生可以省去hash表的方法。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct SelectItem
{
int selected;
int notSelected;
};
SelectItem DFS(TreeNode* o)
{
if(!o)return {0,0};
auto l=DFS(o->left);
auto r=DFS(o->right);
int select=o->val+l.notSelected+r.notSelected;
int notSelect=max(l.selected,l.notSelected)+max(r.selected,r.notSelected);
return {select,notSelect};
}
int rob(TreeNode* root) {
auto result=DFS(root);
return max(result.selected,result.notSelected);
}
};