本实验取材于浙江大学《数据结构》,听过课的同学都知道,生成一棵树二叉树的方法很多,因此今天的层序生成二叉树是建立在队列的情况下,源码如下:
测试用例:
12
13
3
4
5
6
7
0
0
8
0
0
9
0
0
0
0
0
0
//层序遍历生成树,让树生成的更快!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NoInfo 0
#define ERROR -1
#define MaxSizel 10
//typedef struct SNode *PtrToSNode;
typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree; /* 二叉树类型 */
struct TNode{ /* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};
struct QNode{
ElementType *Data;
int rear;
int front;
int MaxSize;
};
typedef struct QNode *Queue;
Queue CreateQueue(int MaxSize1);//生成长度为MaxSize的空队列
int IsFullQ(Queue Q);//判断队列Q是否已满
void AddQ(Queue Q,Position item);//将数据元素item插入队列Q中
int IsEmptyQ(Queue Q);//判断队列Q是否为空
ElementType DeleteQ(Queue Q);//将队头数据元素从队列中删除并返回
Queue CreateQueue(int MaxSize1){
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *) malloc(MaxSize1 * sizeof(ElementType));
Q->front = Q->rear = 0;
Q->MaxSize = MaxSize1;
return Q;
}
int IsFullQ(Queue Q){
return ((Q->rear+1)%Q->MaxSize == Q->front);
}
void AddQ(Queue Q,Position item){
if(IsFullQ(Q)){
printf("Queue is full\n");
return ;
}
Q->rear = (Q->rear+1) %Q->MaxSize;
Q->Data[Q->rear] = (int)item;
}
int IsEmptyQ(Queue Q){
return (Q->front == Q->rear);
}
ElementType DeleteQ(Queue Q){
if(IsEmptyQ(Q))
{
printf("Queue is empty\n");
return -1;
}else{
Q->front = (Q->front+1)%Q->MaxSize;
return Q->Data[Q->front];
}
}
BinTree CreateBinTree()
{
ElementType Data;
BinTree BT,T;
Queue Q = CreateQueue(20);
scanf("%d",&Data);
if(Data != 0){
BT = (BinTree)malloc(sizeof(struct TNode));
BT->Data = Data;
BT->Left = BT->Right = NULL;
AddQ(Q,BT);
}else
return NULL;
while(!IsEmptyQ(Q)){
T =(struct TNode *)DeleteQ(Q);
scanf("%d",&Data);
if(Data==NoInfo) T->Left = NULL;
else{
T->Left = (BinTree)malloc(sizeof(struct TNode));
T->Left->Data = Data;
T->Left->Left = T->Left->Left = NULL;
AddQ(Q,T->Left);
}
scanf("%d",&Data);
if(Data==NoInfo) T->Right = NULL;
else{
T->Right = (BinTree)malloc(sizeof(struct TNode));
T->Right->Data = Data;
T->Right->Left = T->Right->Left = NULL;
AddQ(Q,T->Right);
}
}
return BT;
}
void PreorderTraversal(BinTree BT)
{
if(BT){
printf("%d ",BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
}
int main()
{
//freopen("C:\\Users\\Administrator\\Desktop\\test.txt","r",stdin);
BinTree BT = CreateBinTree();
PreorderTraversal(BT);
printf("\n");
return 0;
}
输出结果