二叉树的层次遍历思想就是从根结点开始,从左至右从上层往下层挨个遍历。用一个数组实现的循环队列来实现就比较简单。根结点进入队列,然后出队,根节的左孩子不为空的话左孩子进队,后孩子不为空的话右孩子进队。然后循环如此直到循环队列空为止。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#define tree_size 6//定义二叉树的结点为6
typedef struct BinaryTree{//
char data;//定义数据域
struct BTNode *rChild;
struct BTNode *lChild;
}BT;
BT* create_binary_tree(char data[]){//创建一颗结点数为6的二叉树
BT *node[max];//定义指针数组来循环初始化二叉树的结点
for(int i=0;i<tree_size;i++){
node[i] = (BT*)malloc(sizeof(BT));
node[i]->data = data[i];
}
node[0]->lChild = node[1];//建立结点之间的关系
node[0]->rChild = node[2];
node[1]->lChild = node[3];
node[1]->rChild = node[4];
node[2]->rChild = node[5];
node[2]->lChild = NULL;//这步不能少哦,少了的话可能会出现异常
node[3]->lChild = node[3]->rChild = NULL;
node[4]->lChild = node[4]->rChild = NULL;
node[5]->lChild = node[5]->rChild = NULL;
return node[0];//返回根结点
}
void visit(BT *p){//访问结点函数
if(p!=NULL){
printf("%c\n",p->data);
}
}
void levelTravel(BT *node){//队列实现二叉树的层次遍历
int rear,front;//定义循环队列的头尾位置
BT queue[tree_size];//循环队列
rear = front = 0;
BT *p = NULL;
if(node==NULL){
return;
}
rear = (rear+1)%tree_size;
queue[rear] = node;//根结点入队
while(rear!=front){
front = (front+1)%tree_size;
p = queue[front];//根结点出队
visit(p);
if(p->lChild!=NULL){
rear = (rear+1)%tree_size;
queue[rear] = p->lChild;//左孩子入队
}
if (p->rChild!=NULL) {
rear = (rear+1)%tree_size;
queue[rear] = p->rChild;//右孩子入队
}
}
}
int main(int argc, const char * argv[]) {
char data[] = {'1','2','3','4','5','6'};//定义一个数组来给二叉树的数据域赋值
BT *root = (BT*)malloc(sizeof(BT));
root = create_binary_tree(data);
levelTravel(root);
return 0;
}