用对列实现二叉树的层次输出

层次遍历二叉树,先是根节点而后是下一层的左右孩子,考虑可以使用队列先进先出的特点,按顺序导入第一个节点,后导入第一个节点的左右孩子,此时队列里第二位的是根的左孩子,根节点出对,左孩子成为队首导入他的孩子,依次进行。
    这时就要求可以根据队列首位元素找到他在树种的孩子,出于便捷我就用指针数组直接存储,然后就是简单的查找入队和出队操作。
 #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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_43921974

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值