Share my c code


  • 1
    K

    typedef struct LinkList {
    int val;
    struct LinkList *next;
    }LinkList;

    void LoopTreeAsLayer(struct TreeNode *root, int level, LinkList *level_list, int link_size) {

    if (root == NULL)
        return;
    
    if (level == *link_size) {
        (*link_size)++;
        if (level == 0)
            *level_list = (LinkList*)malloc(sizeof(LinkList) * (*link_size));
        else
            *level_list = (LinkList*)realloc((*level_list), sizeof(LinkList) * (*link_size));
        (*level_list)[level].val = 0;
        (*level_list)[level].next = NULL;
    }
    
    LinkList *new_node = (LinkList*)malloc(sizeof(LinkList));
    new_node->val = root->val;
    new_node->next = (*level_list)[level].next;
    (*level_list)[level].next = new_node;
    (*level_list)[level].val++;
    
    if (root->right != NULL)
        LoopTreeAsLayer(root->right, level + 1, level_list, link_size);
    if (root->left != NULL)
        LoopTreeAsLayer(root->left, level + 1, level_list, link_size);
    

    }

    int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {

    if (root == NULL)
        return NULL;
        
    LinkList *level_list = NULL;
    int level_list_size = 0;
    
    LoopTreeAsLayer(root, 0, &level_list, &level_list_size);
    
    int **return_array = (int**)malloc(sizeof(int*) * level_list_size);
    *columnSizes = (int*)malloc(sizeof(int) * level_list_size);
    
    for (int i = 0; i < level_list_size; i++) {
        LinkList *list = level_list[i].next;
        int index = 0;
    
        (*columnSizes)[i] = level_list[i].val;
        return_array[i] = (int*)malloc(sizeof(int) * level_list[i].val);
        while (list != NULL) {
            LinkList *del = list;
            
            return_array[i][index++] = list->val;
            list = list->next;
            free(del);
        }
    }
    free(level_list);
    *returnSize = level_list_size;
    return return_array;
    

    }


Log in to reply
 

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