文章目录
二叉树的层次遍历
提示:以下是本篇文章正文内容,下面案例可供参考
一、代码实现
代码如下(示例):
#include <stdio.h>
#include <stdlib.h>
//二叉树
typedef struct BiTNode {
BiTNode* lchild, * rchild;
int num;
}BiTNode, * BiTree;
//队列
typedef struct LinkNode {
BiTNode* data;
LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
//初始化
int InitQueue(LinkQueue& L) {
L.front = L.rear = (LinkNode*)malloc(sizeof(LinkNode));
if (L.front == NULL) return 0;
L.front->next = NULL;
}
void visit(BiTree T) {
printf("nmsl\n");
}
//出队列
void PushNode(LinkQueue& L, BiTree T) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = T;
s->next = NULL;
L.rear->next = s;
L.rear = s;
}
void PopNode(LinkQueue& L, BiTree& T1) {
T1 = L.front->next->data;
printf("%d\n", L.front->next->data->num);
L.front = L.front->next;
}
void LevelTraversal(BiTree& T) {
BiTree T1;
LinkQueue L;
InitQueue(L);
PushNode(L, T);
while (L.front != L.rear) {
PopNode(L, T1);
//visit(Tem);
if (T1->lchild != NULL) PushNode(L, T1->lchild);
if (T1->rchild != NULL) PushNode(L, T1->rchild);
}
}
int main() {
BiTree T = (BiTree)malloc(sizeof(BiTNode));
T->num = { 1 };
T->lchild = NULL;
T->rchild = NULL;
BiTree P = (BiTree)malloc(sizeof(BiTNode));
P->num = { 2 };
T->lchild = P;
P->lchild = NULL;
P->rchild = NULL;
BiTree I = (BiTree)malloc(sizeof(BiTNode));
I->num = { 3 };
T->rchild = I;
I->lchild = NULL;
I->rchild = NULL;
BiTree a = (BiTree)malloc(sizeof(BiTNode));
a->num = { 5 };
P->rchild = a;
a->lchild = NULL;
a->rchild = NULL;
LevelTraversal(T);
}
二.运行结果
总结
没什么好总结的