``````/**
* 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:
int rob(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> queue;
queue.push(root);
int round = 0;
int sum_even = 0,sum_odd = 0;
while(!queue.empty())
{
int size = queue.size();
for(int i = 0;i < size;i++)
{
TreeNode* curr = queue.front();
queue.pop();
if(round % 2 == 0)
{
sum_even += curr->val;
}else{
sum_odd += curr->val;
}
if(curr->left) queue.push(curr->left);
if(curr->right) queue.push(curr->right);
}
round += 1;
}

return max(sum_even,sum_odd);
}
};``````

``````/**
* 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:
int rob(TreeNode* root) {
int in_self = 0,ex_self = 0;
//计算不包含root结点和包含root结点所能抢劫的最大值
helper(root,in_self,ex_self);
return max(in_self,ex_self);
}
private:
static void helper(TreeNode* root,int& in_self,int& ex_self)
{
if(!root) return;
int in_self_l = 0,ex_self_l = 0;
int in_self_r = 0,ex_self_r = 0;

helper(root->left,in_self_l,ex_self_l);
helper(root->right,in_self_r,ex_self_r);

//包含了root就不能包含root->left和root->right
in_self = root->val + ex_self_l + ex_self_r;

//不包含root可以包含root->left right，也可以不包含
ex_self = max(in_self_l,ex_self_l) + max(in_self_r,ex_self_r);

}
};``````