把这道题想简单了,本来以为把奇数层累加起来,把偶数层累加起来,然后判断最大值即可,但是忽略了如下case的情形[4,1,null,2,null,3],这里利益最大化是第一层加第四层,那么问题如何处理呢?
按层相加的C++ code

/**
 * 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);
    
    }
};