按層次遍歷二叉樹-用隊列作為緩沖(中等)


 

#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");
}

 

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM