#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define DateType char
#define MAXSIZE 100 //队列的最大容量//
typedef struct CSNode
{
DateType data;
struct CSNode *firdtchild;//第一个孩子
struct CSNode *nextsbling;//该孩子的第一个兄弟
}CSNode,*CSTree;
typedef struct SeqQueue
{
CSTree data[MAXSIZE];//结构体数组
int front,rear;//数组下标
}SeqQueue, *PSeqQueue;
PSeqQueue Init_SeqQueue()//队列初始化
{
PSeqQueue Q;
Q= (PSeqQueue)malloc(sizeof(SeqQueue));
if (Q)
{
Q->front = 0;
Q->rear = 0;
}
return Q;
}
int Empty_SeqQueue(PSeqQueue Q)//返回值:1表示为空,0表示非空//
{
if (Q && Q->front == Q->rear)
return (1);
else
return (0);
}
int In_SeqQueue(PSeqQueue Q, CSTree x)//返回值:1表示成功,-1表示队满溢出//
{
if ((Q->rear + 1) % MAXSIZE == Q->front)
{
printf("队满");
return -1; /*队满不能入队*/
}
else
{
Q->rear = (Q->rear + 1) % MAXSIZE;
Q->data[Q->rear] = x;
return 1; /*入队完成*/
}
}
CSTree Out_SeqQueue(PSeqQueue Q)//出队,返回指针 //
{
CSTree x;
x=(CSTree)malloc(sizeof(CSNode));
if (Empty_SeqQueue(Q)) {
printf("队空");
return -1; /*队空不能出队*/
}
else
{
Q->front = (Q->front + 1) % MAXSIZE;
x= Q->data[Q->front];
return x; /*出队完成*/
}
}
CSTree CreateTree() //创建一棵树
{
CSTree T;
T= (CSTree)malloc(sizeof(CSNode));
PSeqQueue Q;
Q= Init_SeqQueue();//构造一个空队列
char buffChild[20] = { '\0' }; //用于存放孩子们的缓存
printf("请输入树的根结点(字符,以#代表空):\n");
scanf("%c", &buffChild[0]);
if (buffChild[0] != '#')
{
T->data = buffChild[0];
T->nextsbling = NULL; //根结点无兄弟
In_SeqQueue(Q, T); //根结点入队
while (!Empty_SeqQueue(Q))
{
CSTree e;
e = Out_SeqQueue(Q);
printf("请按长幼顺序输入结点%c的孩子(输入的字符串以#结束):\n", e->data);
scanf("%s", buffChild);
if (buffChild[0] != '#')//有孩子
{
CSTree q,p;
q =p= (CSTree)malloc(sizeof(CSNode)); //开辟孩子结点空间
if (!q)
return 0;
q->data = buffChild[0]; //
e->firdtchild = q; //指向第一个孩子
In_SeqQueue(Q, q); //第一个孩子入队
p = q; //指向刚入队的孩子
for (size_t i = 1; i < strlen(buffChild) - 1; ++i) //孩子存在兄弟
{
q = (CSTree)malloc(sizeof(CSNode)); //开辟孩子结点空间
if (!q)
return 0;
q->data = buffChild[i];
p->nextsbling = q;
In_SeqQueue(Q, q);
p = q; //指向刚入队的孩子
}
p->nextsbling = NULL;
}
else//无孩子
{
e->firdtchild = NULL;
}
}
}
else
{
T = NULL;//空树
}
return T;
}
int LevelOrderTraverse( CSTree T)
{
//层序遍历树
PSeqQueue Q;
Q = Init_SeqQueue();//构造一个空队列
if (T)
{
printf("%c ", T->data); //访问结点
In_SeqQueue(Q, T); //根结点排队
while (!Empty_SeqQueue(Q))
{
CSTree e, p;
e = p = (CSTree)malloc(sizeof(CSNode));
e = Out_SeqQueue(Q);
p = e->firdtchild;
while (p)
{
printf("%c ", p->data);
In_SeqQueue(Q, p);
p = p->nextsbling;
}
}
return 1;
}
return 0;
}
void PreOrder(CSTree T)//前序遍历
{
if (T)
{
printf("%c", T->data);
PreOrder(T->firdtchild);
PreOrder(T->nextsbling);
}
}
int main()
{
CSTree T;
T = CreateTree();
printf("按层序遍历该树:");
LevelOrderTraverse(T);
printf("\n");
printf("进行前序遍历:\n");
PreOrder(T);
printf("\n");
system("pause");
return 0;
}
那中序和后序遍历:
void PreOrder(CSTree T)//中序遍历
{
if (T)
{
PreOrder(T->firdtchild);
printf("%c", T->data);
PreOrder(T->nextsbling);
}
}
void PreOrder(CSTree T)//后序遍历
{
if (T)
{
PreOrder(T->firdtchild);
PreOrder(T->nextsbling);
printf("%c", T->data);
}
}