中序遍歷二叉樹(非遞迴演算法 c語言)
#include "stdio.h"
#include "string.h"
#include "malloc.h"
#define NULL 0
#define MAXSIZE 30
typedef struct BiTNode //定義二叉樹資料結構
{
char data;
struct BiTNode *lchild,*rchild;
} BiTNode;
typedef struct Queue //定義順序結構佇列資料結構(層序遍歷需要藉助佇列)
{
struct BiTNode * data[MAXSIZE];
int front,rear;
} Queue;
typedef struct Stack //定義順序結構棧資料結構(非遞迴遍歷二叉樹需要藉助棧)
{
struct BiTNode * data[MAXSIZE];
int top;
} Stack;
bool isEmpty(Queue *);//判佇列是否空
bool InitStack(Stack *& s)//初始化棧
{
if(!(s=(Stack *)malloc(sizeof(Stack))))
{
return false;
}
else
{
s->top=-1;
}
}
bool isFullStack(Stack *s)//判棧是否滿
{
if((s->top)==(MAXSIZE-1))
{
return true;
}
else
return false;
}
bool isEmptyStack(Stack *s)//判棧是否空
{
if((s->top)==-1)
{
return true;
}
else
return false;
}
bool push(Stack *s,BiTNode *&bitnode)//入棧
{
if(!isFullStack(s))
{
s->top++;
s->data[s->top]=bitnode;
return true;
}
else
return false;
}
bool pop(Stack *s,BiTNode *& bitnode)//入棧
{
if(s->top==-1)
{
return false;
}
else
{
bitnode=s->data[s->top];
(s->top)--;
return true;
}
}
bool InitQueue(Queue *& q)//初始化佇列
{
if(!(q=(Queue *)malloc(sizeof(Queue))))
{
return false;
}
else
{
q->front=0;
q->rear=0;
return true;
}
}
void enQueue(Queue *q,BiTNode * data)//入隊
{
if(q->front==(q->rear+1))
{
printf("Queue is full\n");
}
else
{
q->data[q->rear]=data;
q->rear=((q->rear)+1)%MAXSIZE;
}
}
void deQueue(Queue *q,BiTNode *& data)//出隊
{
if(!isEmpty(q))
{
data=q->data[q->front];
q->front=(q->front+1)%MAXSIZE;
}
}
bool isEmpty(Queue *q)//判隊空
{
if(q->front==q->rear)
{
return true;
}
else
return false;
}
void preCreate(BiTNode *& T) //先序遍歷建立二叉樹
{
char ch;
ch=getchar();
if(ch=='#')
T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
printf("Error!");
T->data=ch;
preCreate(T->lchild);
preCreate(T->rchild);
}
}
void inOrderNo(BiTNode * T)//非遞迴進行中序遍歷,藉助於棧
{BiTNode * temp=T;
Stack *s;
InitStack(s);
while(temp!=NULL||!isEmptyStack(s))
{
if(temp!=NULL)
{
if(push(s,temp))
temp=temp->lchild;
else
printf("壓棧失敗\n");
}
else
{
if(pop(s,temp))
{
printf("%c",temp->data);
temp=temp->rchild;
}
else
printf("彈棧失敗\n");
}
}
}
void levelOrder(BiTNode * T)//層序遍歷,藉助於佇列
{
BiTNode * node=T;
Queue * queue=NULL;
InitQueue(queue);
enQueue(queue,T);
while(!isEmpty(queue))
{
deQueue(queue,T);
printf("%c",T->data);
if(T->lchild!=NULL)
enQueue(queue,T->lchild);
if(T->rchild!=NULL)
enQueue(queue,T->rchild);
}
}
int main()
{
BiTNode * bitree=NULL;
preCreate(bitree);//先序遍歷建立二叉樹
printf("\n中序遍歷:(非遞迴)");
inOrderNo(bitree);
printf("\n層序遍歷:");
levelOrder(bitree);
return 0;
}