二叉树层序生成算法

层序生成大意:先根节点,然后左子树,在右子树。之后,输入一个结点,紧跟着是左右子树。为没有,为结点输入为0.
比如结点为 7 3 2 10 9 4 11 0 0 14 0 0 17 0 0 0 0 0 0
输入第一个数据,若为零,则此树为空。
此树为
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
typedef int element;
typedef struct Tnode* bintree;
struct Tnode{
	element data;
	bintree l,r;	
};
typedef struct Node{
	struct Node* next;
	bintree tdata;
}*position;
typedef struct Qnode{
	position front,rear;
}*queue;
queue creatqueue(){
	queue a=(queue)malloc(sizeof(struct Qnode));
	a->front=a->rear=NULL;
	return a;
}
bool isempty(queue q){
	return (q->front==NULL);
}
bool addq(queue q,bintree am){
	position p;
	p=(position)malloc(sizeof(struct Node));
	p->tdata=am;
	p->next=NULL;
	if(q->front==NULL)
	{
		q->front=q->rear=p;
	}
	else
	{
		q->rear->next=p;
		q->rear=p;	
	}
	return true;
}
bintree deletq(queue q){
	if(isempty(q)) return NULL;
	bintree am=q->front->tdata; 
	position tep=q->front;
	if(q->front==q->rear) q->front=q->rear=NULL;
	else q->front=q->front->next;
	free(tep);
	return  am;
}
void freebintree(bintree t)
{	
	if(t){
		
		freebintree(t->l);
		freebintree(t->r);
		free(t);
	}
}
bintree creatbtree(){
	element num;
	queue qq=creatqueue();
	scanf("%d",&num);
	if(num==0) return NULL;
	bintree bt,t;
	bt=(bintree)malloc(sizeof(struct Tnode));
	bt->data=num;
	bt->l=bt->r=NULL;
	addq(qq,bt);
	while(!isempty(qq)){
		t=deletq(qq);
		scanf("%d",&num);
		if(num==0) t->l=NULL;
		else{
			t->l=(bintree)malloc(sizeof(struct Tnode));
			t->l->data=num;
			t->l->l=t->l->r=NULL;
			addq(qq,t->l);
		}
		scanf("%d",&num);
		if(num==0) t->r=NULL;
		else{
			t->r=(bintree)malloc(sizeof(struct Tnode));
			t->r->data=num; 
			t->r->l=t->r->r=NULL;
			addq(qq,t->r); 
		}
	}
	return bt;
}
void disbintree(bintree bt){
	queue q=creatqueue();
	bintree t;
	addq(q,bt);
	while(!isempty(q))
	{
		t=deletq(q);
		printf("%d " ,t->data);
		if(t->l)addq(q,t->l);
		if(t->r)addq(q,t->r);
	}
}
int main(){
	bintree bt=creatbtree();
	disbintree(bt);
	return 0;
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值