二叉树之层次遍历(二)

这个方法遍历二叉树主要是通过队列来遍历,每层每个元素的遍历都会查询,如果此元素有子节点就放入队列中,因为队列是先进先出的性质,所以,可以顺序输出二叉树。下面请看详细代码:
//队列遍历二叉树
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值