Why the result from QJ is different from VS 2010


  • 2
    class Solution {
    
    public:
    
        int sumNumbers(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		static int pathsum = 0;
    		static int sum = 0;
    		if (root != NULL) {
    			pathsum = 10 * pathsum + root->val;
    			if (root->left == NULL && root->right == NULL)
    				sum += pathsum;
    			sumNumbers(root->left);
    			sumNumbers(root->right);
    			pathsum = (pathsum - root ->val) /10 ;
    		}
    		
    		return sum;
        }
    };
    

    I submit this code, and tell me wrong answer:
    Input: {0,1}

    Output: 10

    Expected: 1

    However, when I run my program in VS2010, the answer is 1....


  • 5
    C

    I think your algorithm is right. But you use static vars, which might cause problem. Because maybe OJ just creates one instance of class solution, and uses it on many test cases. So you had better reset them. This is the only reason I can come up with. I am not sure. You can use a vector to track the node instead.


  • 0
    S

    Could you please format your code correctly?


  • 0
    S

    Yes, you are right... THX


  • 0

    Actually the static variable is shared among all instances. See here for more details.


Log in to reply
 

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