码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer32-III从上到下打印二叉树

时间:2020-07-18 11:18:07      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:typedef   打印二叉树   struct   二叉树   png   calloc   cal   malloc   bsp   

技术图片

 

技术图片

 

 

此题和之前的剑指offer32-I、II.从上到下打印二叉树大致相同在BFS的基础上只是添加了一个重排序的过程。具体代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 
11 /**
12  * Return an array of arrays of size *returnSize.
13  * The sizes of the arrays are returned as *returnColumnSizes array.
14  * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
15  */
16  typedef struct queue
17  {
18      int front;
19      int rear;
20      struct TreeNode *data[1009];
21  }QUEUE;
22 int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
23     *returnSize=0;
24     if(root==NULL)
25     {
26         return NULL;
27     }
28     QUEUE *q=(QUEUE *)malloc(sizeof(QUEUE)*1009);
29      q->front=0;
30      q->rear=1;
31      q->data[0]=root;
32     int **res=(int **)malloc(sizeof(int *)*1009);       //定义一个二维数组
33     //bfs
34     while(q->front!=q->rear)
35     {
36         int levelcount=q->rear-q->front;      //二叉树每层的个数也就是数组中每行有多少个数。
37         res[*returnSize]=(int *)calloc(levelcount,sizeof(int)); //给数组中每一行分配levelcount个地址。
38         (*returnColumnSizes)[*returnSize]=levelcount;
39             for(int i=0;i<levelcount;i++)
40             {
41                 if(q->data[(q->front)]->left)
42                 {
43                     q->data[(q->rear)++]=q->data[q->front]->left;
44                 }
45                 if(q->data[(q->front)]->right)
46                 {
47                     q->data[q->rear++]=q->data[q->front]->right;
48                 }
49                 if(*returnSize%2!=0)    //对奇数行号进行重排列
50                 {
51                     res[*returnSize][levelcount-i-1]=q->data[q->front]->val;
52                 }
53                 else
54                 {
55                      res[*returnSize][i]=q->data[q->front]->val;
56                 }
57                 q->front++;
58             }
59         (*returnSize)++;         //记录层数,即二维数组的行数。
60     }
61     return res;
62 }

技术图片

 

剑指offer32-III从上到下打印二叉树

标签:typedef   打印二叉树   struct   二叉树   png   calloc   cal   malloc   bsp   

原文地址:https://www.cnblogs.com/sbb-first-blog/p/13334112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!