c 3ms ,easy undestanding, one queue


  • 0
    A
    typedef struct TreeNode TreeNode;
    int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
        if (root == NULL) return NULL;
        
        int **ans = malloc(sizeof(int *) * 1000);
        *columnSizes = malloc(sizeof(int) * 1000);
        
        TreeNode *queue[2000]; //easy queue
        int first = 0, end = 0;
        queue[end++] = root;
        
        int nodes_cur_level = 1, nodes_next_level = 0, level = 0;
        
        while (first < end) {
            ans[level] = malloc(sizeof(int) * 1000);
            
            for (int i = 0; i < nodes_cur_level && first < end; i++) {
                TreeNode *tmp = queue[first++];
                ans[level][i] = tmp->val;
                
                if (tmp->left) {
                    queue[end++] = tmp->left;
                    nodes_next_level++;
                }
                if (tmp->right) {
                    queue[end++] = tmp->right;
                    nodes_next_level++;
                }
            }
            
            (*columnSizes)[level++] = nodes_cur_level;
            if ((nodes_cur_level = nodes_next_level) == 0) break;
            
            nodes_next_level = 0;
        }
        
        *returnSize = level;
        return ans;
    }
    

  • 0
    D

    @autoria
    hi..a quick question : when I try online environments to run my C program I always have to cast the pointer returned by the malloc into int* or int** but I see that you are not casting it into any data type in initializing "ans" or "columnSizes" ? Any explanation would be great. Thanks


Log in to reply
 

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