题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

控制队列入队操作和读数操作分离就很容易了这题

#include <stdbool.h>
#include <stdlib.h>
int** Print(struct TreeNode* pRoot, int* returnSize, int** returnColumnSizes ) {
    // write code here
    if(pRoot == NULL){
        return NULL;
    }
    int **rtn = malloc(sizeof(int*)*1500);
    struct TreeNode* nodelist[1500];
    *returnSize = 0;
    *returnColumnSizes = malloc(sizeof(int)*1500);
    bool flag = true;
    int i = 0;
    int j = 1;
    nodelist[0] = pRoot;
    while(i<j){
        rtn[*returnSize] = malloc(sizeof(int)*(j-i));
        (*returnColumnSizes)[*returnSize] = j - i; 
        int cc = j;
        int ee = i;
        int index = 0;
        while(i<cc){
            if(nodelist[i]->left!=NULL){
                nodelist[j++] = nodelist[i]->left;
            }
            if(nodelist[i]->right!=NULL){
                nodelist[j++] = nodelist[i]->right;
            }
            i++;
        }
        if(flag){
            while(ee<cc){
                rtn[*returnSize][index++] = nodelist[ee++]->val;
            }
        }else{
            cc = cc-1;
            while(ee<=cc){
                rtn[*returnSize][index++] = nodelist[cc--]->val;
            }
        }
        *returnSize +=1;
        flag = !flag;
    }
    
    return rtn;
}

全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
xwqlikepsl:感觉很厉害啊,慢慢找
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务