二叉树层序生成算法

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

#include
#include
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;
}

你可能感兴趣的:(算法)