(1) 每个Node分为要用和不要用两种case。
(2) 如果当前root要被使用,那么相邻的node遍布可以使用;
(3) 如果当前node不被使用,那么相邻node可以用也可以不用,找到最大值相加。
class Solution {
public:
//select----------是root使用
//non-------------root不被使用
void dfs(TreeNode* root,int &select, int &non){
if(root == NULL) return;
int ls = 0; //use left
int ln = 0; //not use left
int rs = 0; //use right
int rn = 0; // not use right
dfs(root->left,ls,ln);
dfs(root->right,rs,rn);
select += ln + rn + root->val; //root的值使用了,left,right的值都不可是使用.
non += max(ls,ln) + max(rs,rn); //not use root. max(left) + max(right);
}
int rob(TreeNode* root) {
if(root == NULL)
return 0;
int select = 0;
int non = 0;
dfs(root,select,non);
return max(select,non);
}
};