A strange problem caused by my c code by DFS.


  • 0
    W

    Here is my c code:

    int** levelOrderBottom(struct TreeNode* root, int** columnSizes, int* returnSize) {
    if (root == NULL || columnSizes == NULL || returnSize == NULL)
        return NULL;
        
    int** ret = (int**)malloc(sizeof(int*) * 1000);
    int* columnNum = (int*)malloc(sizeof(int) * 1000), *pswap;
    memset(ret, 0, 1000);
    memset(columnNum, 0, 1000);
    struct TreeNode* stack[1000], *cur;
    int level[1000], top = -1, lvl = 0, curlvl = 0, size = 0, swap;
    
    for (int i = 0; i < 1000; i++)
        ret[i] = (int*)malloc(sizeof(int)*1000);
        
    stack[++top] = root;
    level[top] = 0;
    
    while (top != -1) {
        // pop
        curlvl = level[top];
        cur = stack[top];
        ret[curlvl][columnNum[curlvl]++] = cur->val;
        if (curlvl > size)
            size = curlvl;
        top--;
        // push
        if (cur->right != NULL) {
            stack[++top] = cur->right;
            level[top] = curlvl + 1;
        }
        if (cur->left != NULL) {
            stack[++top] = cur->left;
            level[top] = curlvl + 1;
        }
    }
    
    *columnSizes = columnNum;
    *returnSize = size + 1;
    // reverse array
    for (int j = 0; j < size - j; ++j) {
        pswap = ret[j], ret[j] = ret[size-j], ret[size-j] = pswap;
        swap = columnNum[j], columnNum[j] = columnNum[size-j], columnNum[size-j] = swap;
    }
    
    return ret;
    }
    

    but there is a testcase returns Runtime Error.
    the testcase is like [-150,null,-149,null,...,599,null,600,null].


Log in to reply
 

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