Question about House Robber III


  • 0
    B

    I wrote the following code for the question: House Robber III:

    /**
     * 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 {
    private:
        long sumEven=0, sumOdd=0;
    public:
        void helpRobber(TreeNode* root, int level) {
            if(root==NULL)
                return;
                
            if(level%2==0)
                sumEven+=root->val;
            else
                sumOdd+=root->val;
                
            helpRobber(root->left, level+1);
            helpRobber(root->right, level+1);
        }
        
        int rob(TreeNode* root) {
            helpRobber(root, 0);
            return sumOdd>sumEven?sumOdd:sumEven;
        }
    };
    

    Here, I add the nodes values at each level and return the ones with the maximum value. Pretty straight-forward.

    So, for the input [4,1,null,2,null,3], it returns the value 6 (as I expect). However, apparently, the correct answer is 7. Could someone please explain how is 7 the correct answer? Thank you!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.