这个方法遍历二叉树主要是通过队列来遍历,每层每个元素的遍历都会查询,如果此元素有子节点就放入队列中,因为队列是先进先出的性质,所以,可以顺序输出二叉树。下面请看详细代码:
//队列遍历二叉树
#include <stdio.h>
#include <stdlib.h>
//创建树节点
typedef struct Node{
int d;
struct Node *lchild;
struct Node *rchild;
}Tree_Node,*Tree;
//创建队列节点
typedef struct node
{
Tree data;
struct node *next;
}linklist;
typedef struct list
{
linklist *front,*rear;
int num;
}link,*linkqueue;
//初始化空队
void InitEmpty(linkqueue &q)
{
q->front=q->rear=(linklist*)malloc(sizeof(linklist));
q->front->next=NULL;
q->rear->next=NULL;
}
//置空队
void SetEmptyQueue(linkqueue &q)
{
q->front->next=NULL;
q->front=q->rear;
}
//判断空队
int IsEmpty(linkqueue &q)
{
if(q->front==q->rear)
{
return 1;
}else{
return 0;
}
//return ((q->front==q->rear)?1:0);
}
//元素入队
int InQueue(linkqueue &q,Tree e)
{
q->rear->next=(linklist*)malloc(sizeof(linklist));;
q->rear=q->rear->next;
q->rear->data=e;
q->rear->next=NULL;
q->num++;
return 0;
}
//元素出队
int OutQueue(linkqueue &q)
{
int e;
linklist *p;
if(IsEmpty(q))
{
printf("空队!\n");
return 0;
}
p=q->front;
q->front=p->next;
e=q->front->data->d;
printf("%d",e);
free(p);
q->num--;
return 0;
}
//创建树
Tree CreateTree()
{
Tree t=NULL;
int a;
scanf("%d",&a);
if(a==-1)
{
return t;
}else{
t=(Tree)malloc(sizeof(Tree_Node));
t->d=a;
t->lchild=CreateTree();
t->rchild=CreateTree();
return t;
}
}
Tree ShowFront(linkqueue &q)
{
Tree e;
if(IsEmpty(q))
{
printf("空队!\n");
return 0;
}else{
e=q->front->next->data;
return e;
}
}
//遍历
void traverse(Tree &t,linkqueue &m)
{
Tree p;
InQueue(m,t);
while(!IsEmpty(m))
{
p = ShowFront(m); //通过取头结点的方式得到每一层的第一个元素,这很关键。
OutQueue(m);
if(p->lchild!=NULL)
{
InQueue(m,p->lchild);
}
if(p->rchild!=NULL)
{
InQueue(m,p->rchild);
}
}
}
int main ()
{
int e;
//指向链队列
linkqueue m;
m=(linkqueue)malloc(sizeof(link));
InitEmpty(m);
SetEmptyQueue(m);
Tree t;
t=CreateTree();
traverse(t,m);
return 0;
}