• 二叉树的层次遍历


    一、实验内容

    【问题描述】设计一个能够对链式存储的二叉树进行层次遍历的演示程序。

    【基本要求】从键盘输入数据,创建一棵二叉树,然后将层次编历的结果输出。

    【测试数据】输入的二叉树见教材127页图6.8(b),输出为ABCDEFG。

    二、实验目的

    1.熟悉掌握二叉树和队列的基本操作。

    2.培养运用队列解决问题的能力。

    三、程序代码

    #include "stdio.h"
    #include "stdlib.h"
    #define MAX 1000000

    typedef struct Bitree
    {
     char data;
     struct Bitree *lchild,*rchild;
    }Bitree;

    typedef struct
    {
     Bitree *st[MAX];
     int f,r;//队头和队尾
    }Qu;

    //Bitree *T;

    void InitBitree(Bitree **t)
    {
     *t=NULL;
    }

    int CreateBitree(Bitree **t)//创造二叉树
    {
     char ch;
     scanf("%c",&ch);
     
     if(ch==' ')
      *t=NULL;
     else
     {
      if(!(*t=(Bitree *)malloc(sizeof(Bitree))))
       exit(-1);
      (*t)->data=ch;
      CreateBitree(&(*t)->lchild);
      CreateBitree(&(*t)->rchild);
     }
     return 1;
    }

    void Translevel(Bitree *t)
    {
     //Bitree *s;
     Qu *q=(Qu *)malloc(sizeof(Qu));//这里要初始化
     q->f=0;
     q->r=0;
     
     if(t!=NULL)
      printf("%c",t->data);
     
     q->st[q->r]=t;
     (q->r)++;
     while((q->f)<(q->r))
     {
      t=q->st[q->f];
      (q->f)++;
      if(t->lchild!=NULL)
      {
       q->st[q->r]=t->lchild;
       printf("%c",t->lchild->data);
       (q->r)++;
      }
      if(t->rchild!=NULL)
      {
       q->st[q->r]=t->rchild;
       printf("%c",t->rchild->data);
       (q->r)++;
      }
     }
    }

    int main()
    {
     Bitree *T;

     InitBitree(&T);

     printf("请输入你要创建的二叉树:\n");
     CreateBitree(&T);
     printf("输出层次遍历的二叉树:\n");
     Translevel(T);
     printf("\n\n");

     return 0;
    }

    当输入ABC  DE G  F   结果是ABCDEFG

    起初呢,创造二叉树那儿忘记传过去地址了,一直错,原来是自己数据结构掌握的不好……记得传地址啊,那样所建的树在主程序中才可以用(自己的理解)~~~^_^

    不知道有没有错啊,反正输进去的上述输入结果是预料的……

  • 相关阅读:
    lazarus自带的DBGrid隔行颜色交替的设置
    lazarus 获取硬件ID的函数,适用于linux和win
    解决linux每次重启系统后编写的cef4delphi程序都要解锁密钥环
    lazarus fpcupdeluxe版小工具(linux for aarch64)
    lazarus 模拟menubutton
    lazarus Ehlib的DBLookupComboboxEh控件在linux使用经验
    编译SQLite libsqlite3.so文件
    lazarus在linux arm64使用SQLite数据加密的方法
    lazarus 使用zeos ZQuery.filter注意事项
    从零开始配置 vim(9)——初始配置
  • 原文地址:https://www.cnblogs.com/Shirlies/p/2275635.html
Copyright © 2020-2023  润新知