其他分享
首页 > 其他分享> > LeetCode 107. 二叉树的层序遍历 II

LeetCode 107. 二叉树的层序遍历 II

作者:互联网

在这里插入图片描述
思路:在102题的基础上修改代码,增加一个反转就可以了。

int** levelOrderBottom(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    *returnSize = 0;
    if(root==NULL)
        return NULL;
    int **res =malloc(sizeof(int*)*2000);
    *returnColumnSizes = malloc(sizeof(int)*2000);
    struct TreeNode *cur;
    struct TreeNode *queue[2000];
    int front = 0,rear=0;
    queue[rear++] = root;
    while(front!=rear){
        int colSize = 0;
        int last = rear;
        res[*returnSize] = malloc(sizeof(int)*(last-front));
        while(front<last){
            cur = queue[front++];
            res[*returnSize][colSize++] = cur->val;
            if(cur->left!=NULL)
                queue[rear++] = cur->left;
            if(cur->right!=NULL)
                queue[rear++] =cur->right;
        }
        (*returnColumnSizes)[*returnSize] = colSize;
        (*returnSize) ++;
    }
    for(int i=0; i*2<(*returnSize);i++){
        int *temp = res[i];
        res[i] = res[(*returnSize) - i - 1];
        res[(*returnSize) - i - 1] = temp ;

        int temp2 = (*returnColumnSizes)[i];
        (*returnColumnSizes)[i] = (*returnColumnSizes)[(*returnSize) - i - 1];
        (*returnColumnSizes)[(*returnSize) - i - 1] = temp2;
    }
    return res;
}

标签:cur,returnSize,int,res,层序,二叉树,returnColumnSizes,107,rear
来源: https://blog.csdn.net/Zzh1110/article/details/121853360