按层次遍历二叉树-用队列作为缓冲(中等)

 

#include <stdio.h>
#include <stdlib.h>

//定义二叉树的结点
typedef struct btnode
{
  char data;
  struct btnode *lchild,*rchild;
}bitree,*Bitree;

//队列结点的定义
typedef struct LinkQueueNode
{
  bitree *data; //队列结点的数据域是二叉树的结点
  struct LinkQueueNode *next;
}LKQueNode;

//定义队列
typedef struct LKQueue
{
  LKQueNode *front,*rear;
}LKQue;

//初始化队列
void InitQueue(LKQue *LQ)
{
  LKQueNode *p; //定义一个队列结点的指针
  p=(LKQueNode *)malloc(sizeof(LKQueNode));//内存分配一个结点空间,由指针p指向
  LQ->front=p;
  LQ->rear=p;
  LQ->front->next=NULL; //队头指针和队尾指针都指向新结点,并将新结点的指针域置空
}

//判断队列是否为空队列
int EmptyQueue(LKQue *LQ)
{
  if(LQ->front==LQ->rear)
    return 1;
  else
    return 0;
}

//入队操作
void EnQueue(LKQue *LQ,Bitree x) //入队元素为二叉树的整个结点
{
  LKQueNode *p;
  p=(LKQueNode *)malloc(sizeof(LKQueNode));
  p->data=x; //二叉树的结点是队列结点的数据域
  p->next=NULL;
  LQ->rear->next=p;
  LQ->rear=p;
}

//出队操作
int OutQueue(LKQue *LQ)
{
  LKQueNode *s;
  if(EmptyQueue(LQ))
  {
    exit(0);
    return 0;
  }
  else
  {
    s=(LQ->front)->next;
    (LQ->front)->next=s->next;
    if(s->next==NULL)
      LQ->rear=LQ->front;
    free(s);
    return 1;
  }
}

//取队首元素
Bitree GetHead(LKQue *LQ) //队首结点的数据是二叉树的结点,所以要用Bitree声明函数
{ //类型
  LKQueNode *p;
  bitree *q;
  if(EmptyQueue(LQ))
    return q;
  else
  {
    p=(LQ->front)->next;
    return p->data;
  }
}

//创建二叉树
Bitree CreateBinTree()
{
  char ch;
  Bitree t;
  ch=getchar();
  if(ch == '#')
    t=NULL;
  else
  {
    t=(Bitree)malloc(sizeof(bitree)); //分配二叉树的结点
    t->data=ch;
    t->lchild=CreateBinTree();
    t->rchild=CreateBinTree();
  }
  return t;
}

//按层次遍历
void LevelOrder(Bitree T)
{
  LKQue Q;
  Bitree p;
  InitQueue(&Q);
  if(T!=NULL)
  {
    EnQueue(&Q,T);
    while(!EmptyQueue(&Q))
    {
      p=GetHead(&Q);
      OutQueue(&Q);
      printf("%c",p->data);
      if(p->lchild!=NULL)
        EnQueue(&Q,p->lchild);
      if(p->rchild!=NULL)
        EnQueue(&Q,p->rchild);
    }
  }
}

//主函数
void main()
{
  Bitree TT;
  printf("按先序序列输入结点序列,‘#’代表空。\n");
  printf("例如:ABD#C##E##G#FH###\n");
  TT=CreateBinTree();
  printf("层次遍历序列为:\n");
  LevelOrder(TT);
  printf("\n");
}

 

 

运行结果:

 

posted @ 2019-08-03 16:30  bobo哥  阅读(866)  评论(0编辑  收藏  举报