二叉樹層次遍歷(C語言實現)
阿新 • • 發佈:2019-02-15
經過兩天長時間的學習, 通過研究佇列以及二叉樹的相關性質,終於寫出了二叉樹的層次遍歷。
該實現的核心就是使用佇列,每次把訪問到的節點的左右子樹放到佇列裡面去,出隊的時候同樣操作!
感謝@原來如此 , @AlexMok ,兩位同學,在小組相互學習的過程中收穫良多!
下面放出實現原始碼:
#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 20
/*********定義兩個結構體*********/
typedef struct BTree
{
char data;
struct BTree *lchild;
struct BTree *rchild;
}BTree;
typedef struct CircleQueue
{
int num;
int front;
int rear;
BTree *p;
}CircleQueue;
/**********************************佇列部分***********************************/
/**********初始化佇列*****************/
CircleQueue * InitQueue()
{
CircleQueue *q = malloc(sizeof(CircleQueue));
q->p = malloc(MAXSIZE *(sizeof(BTree)));
q->front = q->rear = 0 ;
q->num = 0;
return q;
}
/**************入隊操作***************/
int InQueue(CircleQueue *q, BTree t)
{
if((q->rear + 1) % MAXSIZE == q->front)
{
printf("The Queue is Full\n");
return -1;
}
else
{
q->rear = (q->rear + 1) % MAXSIZE;
q->p[q->rear] = t;
q->num++;
}
return 1;
}
BTree OutQueue(CircleQueue *q, BTree *t)
{
if(q->num == 0)
{
printf("The Queue is already empty!\n");
exit(0);
}
else
{
q->front = (q->front + 1) % MAXSIZE;
*t = q->p[q->front];
printf("%c" , t->data);
q->num--;
}
return *t;
}
/***********************************二叉樹部分************************************8************/
/***********建立二叉樹*****************/
BTree *CreateBTree()
{
BTree *T; //T是指向結構體元素的指標
char ch;
scanf("%ch", &ch); //輸入節點資料
if(ch == '#')
{
T = NULL; //返回空指標
}
else
{
T = malloc(sizeof(BTree)); //開闢儲存空間
T->data = ch; //儲存資料元素
T->lchild = CreateBTree(); //先序建立左子樹
T->rchild = CreateBTree(); //先序建立右子樹
}
return T;
}
/**********先序遍歷二叉樹************/
void PreOrderTraverse(BTree *T) //先序遍歷函式
{
if(T)
{
printf("%c", T->data); //輸出當前結點資料
PreOrderTraverse(T->lchild); //先序遍歷左子樹
PreOrderTraverse(T->rchild); //先序遍歷右子樹
}
}
/***********層次遍歷二叉樹***********/
void Printbylevel(BTree *T)
{
BTree *tmp = T;
CircleQueue *q ;
q = InitQueue();
if(T == NULL)
{
printf("根節點為空") ; //根節點為空,返回-1
}
else
{
InQueue(q, *tmp); //根節點(非指標)入隊
}
while(q->num) //佇列不為空
{
OutQueue(q,tmp); //指標出隊//輸出出隊元素
if(tmp->lchild) //左子樹不為空
{
InQueue(q, *tmp->lchild);//左子樹入隊
}
if(tmp->rchild) //右子樹不為空
{
InQueue(q, *tmp->rchild);//右子樹入隊
}
}
}
int main()
{
BTree *t;
t = CreateBTree();
printf("The pre order is : ");
PreOrderTraverse(t);
printf("\nThe Level Order is : ");
Printbylevel(t);
return 0;
}
程式碼的註釋也比較詳細,適合各位朋友互相參考,歡迎留言交流!!