ps:2018/7/15
自己花了一晚上的时间写的二叉树的层序遍历,但是感觉有点小瑕疵,各位大佬帮忙看看
Moni.h
#ifndef _Moni_H
#define _Moni_H
struct cenxu;
struct queue;
typedef struct cenxu * abc;
typedef struct queue * adf;
void initQueue(adf q);//初始化队列
void shuchushihua(abc p);//初始化树
abc dequeue(adf q);//删除队列元素
int EmptyQueue(adf q);//判断队列是否为空
void inqueue(adf q,abc p);//插入到队列
abc creat(abc p);//把元素插入到树中
void ceng(adf q, abc p);//层序遍历
#endif // !_Moni_H
moni.cpp
# include<stdio.h>
# include <stdlib.h>
# include "moni.h"
#include "malloc.h"
# define max 100
struct cenxu
{
struct cenxu* lchild;
struct cenxu* rchild;
char a;
};
struct queue
{
int rear;
int front;
struct cenxu* K[max];
};
typedef struct cenxu * abc;
typedef struct queue * adf;
void shuchushihua(abc p)//初始化树
{
p->lchild = NULL;
p->rchild = NULL;
}
void initQueue(adf q)//初始化队列
{
if (q != NULL)
{
q->front = q->rear = 0;
q->K[max] =(abc) malloc((sizeof(abc))*max);
if (q->K[max] == NULL)
{
printf("error");
}
}
}
abc dequeue(adf q)//删除队列元素
{
return q->K[(q->front)++];
}
int EmptyQueue(adf q)//判断队列是否为空
{
if ((q->front) == (q->rear))
{
return 1;
}
else
{
return 0;
}
}
abc creat(abc p)//把元素插入到树中
{
char ch;
ch = getchar();
if (ch =='#')
{
p= NULL;
}
else
{
if (!(p = (struct cenxu*)malloc(sizeof(struct cenxu))))
printf("Error!");
shuchushihua(p);
p->a = ch;
p->lchild=creat(p->lchild);
p->rchild=creat(p->rchild);
}
return p;
}
void inqueue(adf q, abc p)//插入到队列
{
if (q->rear == max)
{
printf("队列已满!");
}
else
q->K[(q->rear)++] = p;
}
void ceng(adf q, abc p)//层序遍历
{
abc t;
t = p;
if (t != NULL)
{
inqueue(q, t);
}
while (!EmptyQueue(q))
{
t= dequeue(q);
printf("%c", t->a);
if (p->lchild!=NULL)
{
inqueue(q, t->lchild);
}
if (p->rchild != NULL)
{
inqueue(q, t->rchild);
}
}
}
main.cpp
# include "malloc.h"
#include <stdlib.h>
int main(void)
{
adf q;
q = (adf)malloc(sizeof(struct queue*));
abc p;
p = (abc)malloc(sizeof(struct cenxu*));
initQueue(q);
p = creat(p);
ceng(q,p);
system("pause");
return 0;
}