Why don't use global variable??


  • 0
    S

    Hi, everyone, I newbee in this group.
    How are you ?

    why didn't accept same code just difference in using local variable and global varable?

    ---------------------------using global variable ( it doesn't accept in sever but work in local test program)----------

    int * preorder = NULL;  
    int* preorderTraversal(struct TreeNode* root, int* returnSize) { 
    
        // preorder's order : root -> left -> right 
        if(root == NULL )    //error check     
            return NULL; 
        else 
        { 
             preorder = (int*)realloc(preorder, ((*returnSize)+1)*sizeof(int));       
      
             while(preorder == NULL) //error check and reallocation 
             preorder = (int*)realloc(preorder, ((*returnSize)+1)*sizeof(int)); 
      
             preorder[*returnSize] = root->val; 
             (*returnSize)++;  
         } 
         preorderTraversal(root->left, returnSize); // go left leaf
         preorderTraversal(root->right, returnSize); // go right leaf
            
         return preorder;    
    
    } 
    

    ---------------------using local variable ( it doesn't diffrence from upper, just using only local variable-----

    //same function as preorderTraversal, except third variable to use local variable
    int* preorderTraversal2(struct TreeNode* root, int* returnSize, int * preorder); 
     
    int* preorderTraversal(struct TreeNode* root, int* returnSize) { 
    
        int * preorder = NULL; 
     
        preorder = preorderTraversal2(root, returnSize, preorder); 
     
        return preorder; 
    } 
    
    int* preorderTraversal2(struct TreeNode* root, int* returnSize, int * preorder) { 
    
        // preorder's order : root -> left -> right 
        //error check     
        if(root == NULL ) 
             return NULL;  
        else 
        { 
              preorder = (int*)realloc(preorder, ((*returnSize)+1)*sizeof(int));       
              //error check 
              while(preorder == NULL) 
                     preorder = (int*)realloc(preorder, ((*returnSize)+1)*sizeof(int)); 
         
              preorder[*returnSize] = root->val; 
              (*returnSize)++;  
         } 
         preorderTraversal2(root->left, returnSize,preorder); 
         preorderTraversal2(root->right, returnSize, preorder); 
         return preorder; 
    } 
    

    thanks for your help.


  • 0

    Because your global variable isn't reset (to NULL) between the test cases.


Log in to reply
 

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