层次遍历二叉树,先是根节点而后是下一层的左右孩子,考虑可以使用队列先进先出的特点,按顺序导入第一个节点,后导入第一个节点的左右孩子,此时队列里第二位的是根的左孩子,根节点出对,左孩子成为队首导入他的孩子,依次进行。
这时就要求可以根据队列首位元素找到他在树种的孩子,出于便捷我就用指针数组直接存储,然后就是简单的查找入队和出队操作。
#include <stdio.h>
#include <stdlib.h>
typedef struct BTree
{
char str;
struct BTree *lchild;
struct BTree *rchild;
}btree;
typedef struct
{
struct btree* data[20];;
int front;
int rear;
}queque;
btree *creatree()
{
char v;
btree *s=NULL;
scanf("%c",&v);
if(v==' ')
{
s=NULL;}
else
{
s=(btree *)malloc(sizeof(btree));
s->str=v;
s->rchild=creatree();
s->lchild=creatree();
}
return s;
}
void initque(queque *q)
{
q->front=q->rear=0;
}
void enterque(queque *q,btree *s)
{
if((q->rear+1)%20==q->front)
{
printf("队列已满\n");
}
else
{
q->data[q->rear]=s;
q->rear=(q->rear+1);
}
}
btree *popque(queque *q)
{
btree *c;
c=(btree *)malloc(sizeof(btree));
if(q->front==q->rear)
{
printf("队列一空\n");
return NULL;
}
else{
c=q->data[q->front];
q->front=(q->front+1);
return c;
}
}
int EmptyQue(queque *q)
{
if(q->front==q->rear)
return 1;
else
return 0;
}
btree *greathead(queque *q)
{
if(EmptyQue(q))
return NULL;
else
return q->data[q->front];
}
void gradation(btree *s,queque *q)
{
btree *a;
a=(btree *)malloc(sizeof(btree));
enterque(q,s);
while(!EmptyQue(q))
{
a=greathead(q);
popque(q);
printf("%c ",a->str);
if(a->rchild!=NULL)
enterque(q,a->rchild);
if(a->lchild!=NULL)
enterque(q,a->lchild);
}
}
int main(int argc, char *argv[])
{`
char d;
btree *p=NULL;
queque *q=(queque *)malloc(sizeof(queque));
initque(q);
printf("输入字符以创建树\n");
p=creatree();
printf("层次输出\n");
gradation(p,q);
if(q->front!=q->rear)
{
d=popque(q);
printf("%c",d);
}
return 0;
}
用对列实现二叉树的层次输出
最新推荐文章于 2022-06-05 18:06:34 发布