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


    此题和之前的剑指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 }

  • 相关阅读:
    OpenStack Nova Release(Rocky to Train)
    5G 与 MEC 边缘计算
    Cinder LVM Oversubscription in thin provisioning
    浅析视频云行业及实现技术
    虚拟化技术实现 — KVM 的 CPU 虚拟化
    虚拟化技术实现 — QEMU-KVM
    云计算与虚拟化技术发展编年史
    计算机组成原理 — FPGA 现场可编程门阵列
    Installutil.exe 注册exe
    ASP.NET MVC- 布署
  • 原文地址:https://www.cnblogs.com/sbb-first-blog/p/13334112.html
Copyright © 2020-2023  润新知