Please help with Runtime Error


  • 0
    Q
    int* preorderTraversal(struct TreeNode* root, int* returnSize) 
    {
        static int *result = NULL;
        if (!result)  {
            result = (int *) malloc(256 * sizeof(int));
            *returnSize = 0;
        }
        if (root){
            result[(*returnSize)++] = root->val;
            preorderTraversal(root->left, returnSize);
            preorderTraversal(root->right, returnSize);
        }
        return result;
    }
    

    Last executed input: [3,1,null,2,null,null,4]

    I have tested the code on my local machine and it works fine (for this particular input).
    Appreciate if anyone can give hints on why the code fails.

    Thank you in advance.


  • 1
    Q

    I think I figured it out. So I write down something in the hope that somebody else may find it useful.

    I got it from the answer by ManuelP to the following question.

    why don't use global variable??
    https://leetcode.com/discuss/55768/why-dont-use-global-variable

    The reason of the Runtime Error is that the variable result is not set to NULL between test cases.

    So it is better to use a local variable.


Log in to reply
 

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