按層次遍歷二叉樹,用隊列作為緩沖



//設立一個隊列Q,用於存放結點,以保證二叉樹結點按照層次順序從左到右進入隊列。若二叉樹bt非空,首先,
//將根結點插入隊列,然后,從隊列中刪除一個結點,訪問該結點,並將該結點的孩子結點(如果有的話)插入
//隊列。
#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
{
  LinkQueueNode *front,*rear;
}LKQue;

//初始化隊列
void InitQueue(LKQue * LQ)
{
  LKQueNode *p;
  p=(LinkQueueNode *)malloc(sizeof(LinkQueueNode));
  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=(LinkQueueNode *)malloc(sizeof(LinkQueueNode));
  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)
{
  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 visit(Bitree pp)
{
  printf("%c ",pp->data);
}

//按層遍歷二叉樹
void LevelOrder(Bitree T)
{
  LKQue Q;
  Bitree p;
  InitQueue(&Q);
  if(T!=NULL)
  {
    EnQueue(&Q,T);
    while(!EmptyQueue(&Q))
    {
      p=GetHead(&Q);
      OutQueue(&Q);
      visit(p);
      if(p->lchild!=NULL)
        EnQueue(&Q,p->lchild);
      if(p->rchild!=NULL)
        EnQueue(&Q,p->rchild);
    }
  }
}

//主函數
void main()
{
  Bitree TT;
  printf("按層次遍歷二叉樹,借助隊列作為緩沖,空指針用‘#’表示。\n");
  printf("例如:ABD#E##F##C#GH### \n");
  TT=CreateBinTree();
  printf("層次遍歷序列為:\n");
  LevelOrder(TT);
  printf("\n");
  system("pause");
}

 

 

 

 

 


免責聲明!

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



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