#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
#define QUEUESIZE 5
typedef struct BiNode{
char data;
struct BiNode *lchild, *rchild;
}BiNode;
typedef struct{
BiNode *d[QUEUESIZE]; //指向队列存储空间
int front; //队首下标
int rear; //队尾下标
}Queue;
bool isFull(Queue *);
bool isEmpty(Queue *);
void initCirQueue(Queue *);
void initCirQueue(Queue *q){
q->front=QUEUESIZE-1;
q->rear=-1;
}
bool enQueue(Queue *q,BiNode *bt){ //入队
if(!isFull(q)){
q->rear=(q->rear+1)%QUEUESIZE;
q->d[q->rear]=bt;
return true;
}else
return false;
}
BiNode* deQueue(Queue *q,BiNode **p){ //出队
if(!isEmpty(q)){
q->front=(q->front+1)%QUEUESIZE;
*p=q->d[q->front];
return true;
}else
return false;
}
bool isFull(Queue *q){ //判断队列是否为满
if((q->rear+1)%QUEUESIZE==q->front)
return true;
else
return false;
}
bool isEmpty(Queue *q){
if(q->rear==-1||q->front==q->rear)
return true;
else
return false;
}
char getval(char *str){
static int i=0;
return str[i++]; //*(str+i++);
}
BiNode * create(BiNode *bt,char *str){ //创建二叉树
char ch=getval(str);
if(ch=='#'){
bt=NULL;
}else{
bt=(BiNode *)malloc(sizeof(BiNode));
bt->data=ch;
bt->lchild=create(bt->lchild,str);
bt->rchild=create(bt->rchild,str);
}
return bt;
}
void release(BiNode **bt){ //销毁二叉树
if(*bt==NULL){
return;
}
else{
release(&((*bt)->lchild));
release(&((*bt)->rchild));
free(*bt);
*bt=NULL;
}
}
void preOrder(BiNode *bt){ //前序遍历
if(bt==NULL){
printf("#");
return;
}
else{
printf("%c",bt->data);
preOrder(bt->lchild);
preOrder(bt->rchild);
}
}
void inOrder(BiNode *bt){ //中序遍历
if(bt==NULL){
printf("#");
return;
}
else{
inOrder(bt->lchild);
printf("%c",bt->data);
inOrder(bt->rchild);
}
}
void postOrder(BiNode *bt){ //后续遍历
if(bt==NULL){
printf("#");
return;
}
else{
postOrder(bt->lchild);
postOrder(bt->rchild);
printf("%c",bt->data);
}
}
void leverOrder(BiNode *bt){ //层序遍历
Queue q;
BiNode *p;
initCirQueue(&q); //初始化队列
enQueue(&q,bt); //根节点指针入队
while(!isEmpty(&q)){ //队不为空,则循环
deQueue(&q,&p); //出队节点p
printf("%c",p->data); //访问节点p
if(p->lchild!=NULL)
enQueue(&q,p->lchild); //有左孩子时将其入队
if(p->rchild!=NULL)
enQueue(&q,p->rchild); //有右孩子时将其入队
}
}
int main(void){
char *str="ABC##DE#G##F###";
BiNode * root=create(root,str);
preOrder(root);
printf("\n");
inOrder(root);
printf("\n");
postOrder(root);
printf("\n");
leverOrder(root);
release(&root);
printf("\n");
preOrder(root);
return 0;
}