#include<stdio.h>
#include<stdlib.h>
#define max 100
typedef struct Tree
{
char data;
struct Tree *lchild;
struct Tree *rchild;
int ltag,rtag;
}*tree ,Tree;
typedef struct queue{
tree data[max];
int fount,real;
}*queue,Queue;
void InsertTree(tree *t,char *str,int *x)
{
char ch;
ch=*(str+*x);
*x=*x+1;
if(ch!='#')
{
(*t)=(tree)malloc(sizeof (Tree));
(*t)->data=ch;
(*t)->ltag=0;
(*t)->rtag=0;
InsertTree(&((*t)->lchild),str,x);
InsertTree(&((*t)->rchild),str,x);
}else {
*t=NULL;
}
}
//初始化队列
queue queueInit()
{
queue q=(queue)malloc(sizeof (Queue));
if(q){
q->real=0;
q->fount=0;
}
return q;
}
//入队
void Queuepush(queue q,tree t)
{
if((q->real+1)%max==q->fount)
printf("队列满");
q->real=(q->real+1)%max;
q->data[q->real]=t;
}
//出队
void Queuepop(queue q, tree *t )
{
if(q->fount==q->real)
printf("队空");
else {
q->fount=(q->fount+1)%max;
*t=q->data[q->fount];
}
}
//判断队空
int queueEmpty(queue q)
{
if(q->real==q->fount)
return 1;
else {
return 0;
}
}
void Cengci(tree t){
tree s=t;
queue q;
if(s){
q=queueInit();
printf("-->%c",s->data);
Queuepush(q,s);
while (!queueEmpty(q)) {
Queuepop(q,&s);
if(s->lchild){
printf("-->%c",s->lchild->data);
Queuepush(q,s->lchild);
}
if(s->rchild){
printf("-->%c",s->rchild->data);
Queuepush(q,s->rchild);
}
}
}
}
int main()
{
tree t;
// tree pre=NULL;
int x=0;
InsertTree(&t,"ABD#G###CE##FH###",&x);
xianxu(t);
printf("\n");
zhongxu(t);
printf("\n");
houxu(t);
printf("\n");
Cengci(t);
// Inthread(t,&pre);
// InorderTh(t);
return 0;
}
二叉树的层次遍历(非递归)
最新推荐文章于 2024-02-02 16:50:34 发布