日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言實現二叉樹層次遍歷介紹_C 語言

作者:愛學代碼的學生 ? 更新時間: 2022-04-02 編程語言

什么是層次遍歷?

對于一顆二叉樹來說,從根節點開始,按從上到下、從左到右的順序訪問每一個結點。

注:每一個結點有且訪問一次。

那我們如何來實現這個算法呢?

實現原理:

對于二叉樹來說,它是一個遞歸的定義,我們要實現層次遍歷必然要滿足從上到下、從左到右這個要求,從根結點出發,我們可以將所有意義上的根結點都存儲在隊列之中,那我們可以使用隊列先進先出的特點來實現要求的遍歷。

這里我們需要引用隊列來實現。

主體代碼:

 
BiTree InitTree()//二叉樹的創建
{
	BiTree T =(BiTree) malloc(sizeof(Tree));
	char data;
	scanf("%c", &data);
	getchar();
	if (data == '#')//如果data為#則該子樹為空值
		return NULL;
	else {
		T->data = data;
		printf("請輸入%c的左子樹:\n", data);
		T->lchild = InitTree();
		printf("請輸入%c的右子樹:\n", data);
		T->rchild = InitTree();
	}
	return T;
}
void ShowCengci(BiTree T)
{
	LinkQueue qu;
	InitQueue(&qu);//初始化隊列
	enQueue(&qu, T);//根結點入隊
	while (QueueEmpty(qu))//判斷隊列中是否為空
	{
		BiTree S = deQueue(&qu);//根節點出隊
		printf("%c ", S->data);
		if (S->lchild != NULL)//判斷左右子樹是否為空,不為空則入隊
		{
			enQueue(&qu, S->lchild);
		}
		if (S->rchild != NULL)
		{
			enQueue(&qu, S->rchild);
		}
	}

隊列的鏈式實現:

typedef struct BTree
{
	char data;
	struct BTree* lchild;
	struct BTree* rchild;
}Tree,*BiTree;
typedef struct Queue
{
	BiTree data;
	struct Queue* next;
}Qnode,*Queueptr;
typedef struct point
{
	Queueptr front;//頭指針
	Queueptr rear;//尾指針
}LinkQueue;
 
void InitQueue(LinkQueue* qu)
{
	qu->front = qu->rear = (Queueptr)malloc(sizeof(Qnode));
	if (qu->front == NULL)
		return;
}
void enQueue(LinkQueue* qu, BiTree S)
{
	Queueptr p = (Queueptr)malloc(sizeof(Qnode));
	if (p == NULL) {
		return;
	}
	if (S == NULL)
		return;
	p->data = S;
	p->next = NULL;
	qu->rear->next = p;
	qu->rear = p;
}
int QueueEmpty(LinkQueue qu)
{
	if (qu.front != qu.rear)
		return 1;
	else
		return 0;
}
BiTree deQueue(LinkQueue* qu)
{
	if (qu->front == qu->rear)
		return;
	Queueptr p = qu->front->next;
	BiTree q = p->data;
	qu->front->next = p->next;
	if (qu->rear == p)
		qu->rear = qu->front;
	free(p);
	return q;
}

通關上述代碼可以實現對二叉樹的層次遍歷。

總結

原文鏈接:https://blog.csdn.net/Rinki123456/article/details/122569365

欄目分類
最近更新