二叉树的层次遍历
其中心思想为:
源码:
#include<stdio.h>
#include<malloc.h>
typedef struct queue {//定义一个队列结构
struct tree* number[20];
int front;
int rear;
}Queue,*QUEUE;
typedef struct BTree {//定义二叉树的结构
char data;
struct Tree* pLchild;
struct Tree* pRchild;
}BTree,* PBTree;
Queue ps;
PBTree creat_BTree();//创建二叉树
void init_queue();//初始化队列
void push(PBTree pt);//入队列
QUEUE pop();//出队列
void leveltraverse(PBTree pt);//层次遍历
int main() {
PBTree pt= creat_BTree();
init_queue();
printf("二叉树的层次遍历为:");
leveltraverse(pt);
}
PBTree creat_BTree() {//创建二叉树
PBTree pA = (PBTree)malloc(sizeof(BTree));
PBTree pB= (PBTree)malloc(sizeof(BTree));
PBTree pC = (PBTree)malloc(sizeof(BTree));
PBTree pD = (PBTree)malloc(sizeof(BTree));
PBTree pE = (PBTree)malloc(sizeof(BTree));
PBTree pF = (PBTree)malloc(sizeof(BTree));
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pF->data = 'F';
pA->pLchild = pB;
pA->pRchild = pC;
pB->pLchild = pD;
pB->pRchild = pE;
pE->pLchild = pE->pRchild = NULL;
pD->pLchild = pD->pRchild = NULL;
pF->pLchild = pF->pRchild = NULL;
pC->pLchild = pF;
pC->pRchild = NULL;
return pA;
}
void init_queue() {
ps.front = 0;
ps.rear = 0;
}
void push(PBTree pt) {//入队列
ps.rear++;
ps.number[ps.rear] = pt;
}
QUEUE pop() {//出队列
return ps.number[++ps.front];//返回出队列的值
}
void leveltraverse(PBTree pt) {
PBTree temp;//声明一个临时指针
push(pt);//将根节点入队
while (ps.front != ps.rear) {
temp = pop();
printf("%3c", temp->data);//访问当前节点
if (temp->pLchild) {//如果该节点有左子树,把左子树入队
push(temp->pLchild);
}
if (temp->pRchild) {//如果该节点有右子树,把右子树入队
push(temp->pRchild);
}
}
}