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

按之字形顺序打印二叉树

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

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pRoot TreeNode类 
 * @return int整型二维数组
 * @return int* returnSize 返回数组行数
 * @return int** returnColumnSizes 返回数组列数
 */

#include <stdlib.h>
int** Print(struct TreeNode* root, int* returnSize, int** returnColumnSizes ) {
    (*returnSize) = 0;
    if(root == NULL)    return NULL;
    int **level = (int **)malloc(sizeof(int *)*1000);
    *returnColumnSizes =  (int*)malloc(sizeof(int) * 1000);
    int k = 0;
    int head = 750, nhead;
    int tail = 750, ntail;
    struct TreeNode * queue[1500];
    queue[tail++] = root;
    while(head != tail){
        ntail = tail;
        nhead = head;
        k = 0;
        level[*returnSize] = (int *)malloc(sizeof(int)*(ntail - head));
        while((head < ntail)&&(tail > nhead)){
            if((*returnSize)%2 == 0){
                struct TreeNode *p = queue[head];
                level[*returnSize][k++] = p->val; 
                if(p->left)
                    queue[tail++] = p->left;
                if(p->right)
                    queue[tail++] = p->right;
                head++;
            }
            else if((*returnSize)%2 != 0){
                struct TreeNode *p = queue[--tail];
                level[*returnSize][k++] = p->val;
                if(p->right)
                    queue[--head] = p->right;
                if(p->left)
                    queue[--head] = p->left;
            }
        }
        (*returnColumnSizes)[(*returnSize)++] = k;
    }
    return level;
}

全部评论

相关推荐

11-07 13:31
怀化学院 Java
勇敢牛牛不怕难:又疯一个
点赞 评论 收藏
分享
躺尸修仙中:因为很多92的也去卷中小厂,反正投递简历不要钱,面试不要钱,时间冲突就推,不冲突就面试积累经验
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务