Share my C solution with two queues.


  • 0
    C
    int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
    if(!root) return NULL;
    int **res = (int **)malloc(sizeof(int *) * 1000);
    // cur , next are simulated as queues.
    struct TreeNode **cur = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * 1000);
    struct TreeNode **next = (struct TreeNOde **)malloc(sizeof(struct TreeNode *) * 1000);
    (*columnSizes) = (int *)malloc(sizeof(int) * 1000);
    int icursize = 0, icur = 0, inext = 0, ires = 0;
    
    cur[icursize++] = root;
    while(icur < icursize){
        int *level = (int *)malloc(sizeof(int) * 1000);
        int ilevel = 0;
        while(icur < icursize){
            struct TreeNode *tmp = cur[icur++];
            level[ilevel++] = tmp->val;
            if(tmp->left) next[inext++] = tmp->left;
            if(tmp->right) next[inext++] = tmp->right;
        }
        (*columnSizes)[ires] = ilevel;
        res[ires++] = level;
        // swap cur and next
        struct TreeNode **swaptmp = cur;
        cur = next;
        next = swaptmp;
        icursize = inext;
        inext = icur = 0;
    }
    *returnSize = ires;
    return res;
    

    }


Log in to reply
 

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