llllmz

导航

102. 二叉树的层序遍历C

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
    *returnSize=0;
    if(!root) return NULL;
    struct TreeNode* queue[2500];
    int head=0,tail=0,size=1;
    queue[0]=root;
    int* column=(int*)malloc(sizeof(int)*2500);
    int** array=(int**)malloc(sizeof(int*)*2500);
    while(size!=0){
        column[*returnSize]=size;
        array[*returnSize]=(int*)malloc(sizeof(int)*size);
        for(int i=head;i<=tail;i++) array[*returnSize][i-head]=queue[i]->val;
        (*returnSize)++;
        int start=head,end=tail;
        printf("%d%d ",start,end);
        for(;start<=end;start++){
            struct TreeNode* temp=queue[start];
            head++;
            size--;
            if(temp->left){
                queue[++tail]=temp->left;
                size++;
            }
            if(temp->right){
                queue[++tail]=temp->right;
                size++;
            }
        }
        printf("%d %d",size,tail);
    }    
    *returnColumnSizes=column;
    return array;
}

 

posted on 2024-03-20 11:21  神奇的萝卜丝  阅读(41)  评论(0)    收藏  举报