#include "stdio.h"
#include "stdlib.h"
#include "1.h"
#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef int status;
typedef char TElemType;
typedef struct BiTNode{ //二叉链表的定义
TElemType data;
struct BiTNode *lchild,*rchild;
} BiTNode, *BiTree;
typedef BiTree QElemType;
typedef struct
{
QElemType* base;
int front;
int rear;
}SqQueue;//循环队列的定义
//初始化
status InitQueue(SqQueue &Q)
{
Q.base=(QElemType*)malloc(MAXSIZE *sizeof(QElemType));
if(!Q.base)
exit(OVERFLOW);
Q.front=0 ;
Q.rear=0;
return OK;
}
//判断队空
status QueueEmpty(SqQueue Q)
{
if(Q.rear==Q.front)
return TRUE;
else
return FALSE;
}
//取对头元素
status GetHead(SqQueue Q,QElemType &e)
{
if(QueueEmpty(Q))
return ERROR;
else
return (Q.front);
return OK;
}
//求队列长度
int QueueLength(SqQueue Q)
{
return(Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
//入队操作
status EnQueue(SqQueue &Q,QElemType e)
{
if(Q.front==(Q.rear+1)%MAXSIZE)
return ERROR;//队列满
Q.base[Q.rear] = e;
Q.rear=(Q.rear+1)%MAXSIZE;
return OK;
}
//出队操作
status DeQueue(SqQueue &Q,QElemType &e)
{
if(Q.front==Q.rear)
return ERROR;//队列空
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXSIZE;
return OK;
}
/*
下面的是对树的操作
*/
//D.FH...E.G..C..
void createBigTree (BiTree &bt) {
char ch ;
ch = getchar();
if (ch == '#') {
bt = NULL;
}else {
bt = (BiTree)malloc(sizeof(BiTNode));
bt->data = ch;
createBigTree(bt->lchild);
createBigTree (bt->rchild);
}
}
void print(BiTree bt) {
if (bt!=NULL) {
printf("%c ",bt->data);
print(bt->lchild);
print(bt->rchild);
}
}
/*层次遍历
//其思想的核心是使用相应的队列的特点:
// a
/ \
b c
/\
e f
相应的结果应该:a->b->c->e->f;
*/
void divPrint (BiTree bt) {
SqQueue queue;//队列
InitQueue(queue);
EnQueue(queue,bt);
QElemType e = NULL;
while (!QueueEmpty(queue)) {
DeQueue(queue,e);
printf("%c ",e->data);
if (e->lchild!= NULL) {
EnQueue(queue,e->lchild);
}
if (e->rchild!=NULL) {
EnQueue(queue,e->rchild);
}
}
}
void main () {
BiTree tree;
createBigTree(tree);
divPrint(tree);
}
输入:abe##f##c##
输出:
a b c e f