二叉树的层次遍历

一、实验内容

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

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

【测试数据】输入的二叉树见教材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

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

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

原文地址:https://www.cnblogs.com/Shirlies/p/2275635.html