二叉树的层序生成与层序遍历

输入样例:

a b c d f g i 0 0 e 0 0 h 0 0 0 0 0 0

输出样例:

a b c d f g i e h
#include <stdio.h>
#include <stdlib.h>
#define NoInfo '0'
int MaxSize =100;
typedef struct TNode* Position;
typedef char ElementType;
typedef struct TNode* BinTree;
struct TNode{
	ElementType Data;
	BinTree Left;
	BinTree Right;
};
struct QNode{
	BinTree* Data;
	ElementType front,rear;
	int MaxSize;
};
typedef struct QNode* Queue;

Queue CreatQueue(){
	Queue Q=(Queue)malloc(sizeof(struct QNode));
	Q->Data=(BinTree*)malloc(sizeof(BinTree)*MaxSize);
	Q->front=Q->rear=-1;
	Q->MaxSize=MaxSize;
	return Q;
}
int IsEmpty(Queue Q){
	return (Q->front==Q->rear);
}
int IsFull(Queue Q){
	return ((Q->rear+1)%Q->MaxSize==Q->front);
}
bool AddQ(Queue Q,BinTree BT){
	if(IsFull(Q)){
		printf("Queue if full");
		return false;
	}
	else{
		Q->rear=(Q->rear+1)%Q->MaxSize;
		Q->Data[Q->rear]=BT;
		return true; 
	}
}
BinTree Delete(Queue Q){
	if(IsEmpty(Q)){
		printf("Queue is empty");
		return NULL;
	}
	else{
		Q->front=(Q->front+1)%Q->MaxSize;
		return Q->Data[Q->front];
	}
}

BinTree CreateTree(){	//层序生成二叉树 
	ElementType Data;
	BinTree BT,T;
	Queue Q=CreatQueue();
	
	scanf("%c",&Data);
	getchar();
	if(Data !=NoInfo){
		BT=(BinTree)malloc(sizeof(struct TNode));
		BT->Data=Data;
		BT->Left=BT->Right=NULL;
		AddQ(Q,BT);
	}
	else return NULL;
	while(!IsEmpty(Q)){
		T=Delete(Q);
		scanf("%c",&Data);
		getchar();
		if(Data ==NoInfo)
			T->Left=NULL;
		else{
			T->Left=(BinTree)malloc(sizeof(struct TNode));
			T->Left->Data=Data;
			T->Left->Left=T->Left->Right=NULL;
			AddQ(Q,T->Left);
		}
		scanf("%c",&Data);
		getchar();
		if(Data==NoInfo)
			T->Right=NULL;
		else{
			T->Right=(BinTree)malloc(sizeof(struct TNode));
			T->Right->Data=Data;
			T->Right->Left=T->Right->Right=NULL;
			AddQ(Q,T->Right);
		}
	}
	return BT;
}
void LevelorderTraversal(BinTree BT){
	Queue Q;
	BinTree T;
	if(!BT) return;
	
	Q=CreatQueue();
	AddQ(Q,BT);
	int flag=1;
	while(!IsEmpty(Q)){
		T=Delete(Q);
		if(flag) flag=0;
		else printf(" ");
		printf("%c",T->Data);
		if(T->Left) AddQ(Q,T->Left);
		if(T->Right) AddQ(Q,T->Right);
	}
}
int main(){
	BinTree BT=CreateTree();
	LevelorderTraversal(BT);
	return 0;
}


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值