二叉樹層序遍歷

二叉樹層序遍歷

要求 先列出根,然後列出深度爲一的那些節點,在列出深度爲2的節點等等;

剛開始寫這個程序,網上看了幾篇,用了好多指針,初學乍道,沒盯緊指針,有點眼花繚亂,所以按照自己思路寫出來,驗證可以:

#include"stdio.h"
#include"stdlib.h"
#define EOF  (-1)
#define ElementType int       
#define FatalError(str) fprintf(stderr,"%s\n",str),exit(1)
#define MaxSize 100
#define Error 0
#define Ok 1
typedef struct TreeNode *PtrToNode;
typedef PtrToNode Tree;
struct TreeNode
{
ElementType Element;
Tree Left;
Tree Right;
};
struct QueueRecord;
typedef struct QueueRecord *Queue;
void Enqueue(Tree T,Queue Q);
struct QueueRecord
{
int Capacity;//隊列的最大容量
int Front;
int Rear;
int Size;
Tree Tm[MaxSize];
};
/*
   function:CreateQueue()
   功能:初始化隊列
*/
Queue CreateQueue()
{
  Queue Q;
  Q=(Queue)malloc(sizeof(struct QueueRecord));
  Q->Capacity=MaxSize;
  Q->Front=0;
  Q->Rear=0;
  Q->Size=0;
  Q->Tm[Q->Front]=NULL;
  return Q;
}
/*
  函數: Succ(Value,Q)
  描述:Value:隊列的隊尾指標,Q 表示當前隊列
  功能:判斷隊列是否溢出,並使隊尾自加1,返回;
*/
int Succ(int Value,Queue Q)
{
if(++Value==Q->Capacity)
Value=0;
return Value;
}
/*
 函數:Enqueue(Bt,Q)
 描述:Bt爲當前要入隊列的節點,Q爲當前隊列
 功能:使指針所在的節點進入隊列
*/
void Enqueue(Tree Bt,Queue Q)
{
    ++Q->Size;
 Q->Rear=Succ(Q->Rear,Q);
 Q->Tm[Q->Rear]=Bt;
}
/*
 函數:Insert(X,T)
 描述:X,二叉樹中帶插入值,T爲根節點
 功能:將X按照查找二叉樹形式插入樹中
*/
Tree Insert(ElementType X,Tree T)
{
   if(T==NULL)
   {
  T=(Tree)malloc(sizeof(struct TreeNode));
  if(T==NULL)
  FatalError("out of place");
  else
  {
  T->Element=X;
  T->Left=T->Right=NULL;
  }
   }
   else
   {
  if(X<T->Element)
  T->Left=Insert(X,T->Left);
  else
  if(X>T->Element)
  T->Right=Insert(X,T->Right);
   }
  return T;
}
/*
  函數:CreateTree(T1)
  描述 T1爲定義的二叉樹
  功能:將鍵盤中敲入的數創建爲二叉樹
*/
Tree CreateTree(Tree T1)
{
int a;
T1=NULL;
   while(scanf("%d",&a))
   {    if(a==0)       //a爲零時表示結束;
            break;
         else
 T1=Insert(a,T1);
  }
   return T1;
}
/*
  函數:LevelOrder(T1)
  描述:T1爲已經建好的二叉樹
  功能:將二叉樹以層序的方式遍歷,使用Enqueue函數
*/
void LevelOrder(Tree T1)
{  
Queue Q;
Q=CreateQueue();
Tree P;
      P=T1;
 if(P) Enqueue(P,Q);
 ++Q->Front;
   while((Q->Front)<=(Q->Size))
   { 
           P=Q->Tm[Q->Front];
        printf("%d\n",P->Element);
   if(P->Left) Enqueue(P->Left,Q);
   if(P->Right) Enqueue(P->Right,Q);
++Q->Front;
  
   }

}
int main()

Tree HeadT;
HeadT=CreateTree(HeadT);
LevelOrder(HeadT);
return 0;




}

一個相對簡單的程序


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章