#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
#define OVERFLOW -1
typedef struct BiTNode{ //二叉树二叉链表存储表示
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct{ //栈的顺序存储表示
BiTree *base;
BiTree *top;
int stacksize;
}SqStack;
int CreateBiTree(BiTree *T){ //先序法建立一个二叉树
char ch=getchar();
if(ch=='#') *T=NULL;
else{
if(!(*T=(BiTNode *)malloc(sizeof(BiTNode)))) return 0;
(*T)->data=ch;
if((*T)->lchild!=NULL||(*T)->rchild!=NULL){
CreateBiTree(&((*T)->lchild)); //递归调用该函数构造左子树
CreateBiTree(&((*T)->rchild)); //递归调用该函数构造右子树
}
}
return OK;
}
void PrintBiTree(BiTree *T){ //递归先序输出二叉树T
if((*T)!=NULL){
printf("%c",(*T)->data);
PrintBiTree(&((*T)->lchild));
PrintBiTree(&((*T)->rchild));
}
}
int InitStack(SqStack *S){ //创建一个栈S
S->base=(BiTNode *)malloc(STACK_INIT_SIZE*sizeof(BiTNode));
if(!S->base) exit(OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
int StackEmpty(SqStack *S){
if(S->top==S->base)
return 1;
else
return 0;
}
BiTree GetTop(SqStack *S){ //带BiTree返回值类型的GetTop函数返回栈顶元素e
BiTNode *e;
if(S->top==S->base) return NULL;
e=*(S->top-1);
return e;
}
int Push(SqStack *S,BiTree T){ //栈的Push函数
if(S->top-S->base>=S->stacksize)
{
S->base=(BiTNode *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(BiTNode));//若栈空间不足,则增加空间
if(!S->base) exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top)=T; //将树的地址Push进栈,使其在栈的最顶端
S->top++;
return OK;
}
void Pop(SqStack *S){ //栈的Pop函数,弹出栈最顶端的元素
if(S->top==S->base) printf("ERROR!!!");
--S->top;
}
int InOrderTraverse(BiTree *T){ //用栈实现树的中序输出
SqStack S;
BiTNode *p;
InitStack(&S);
Push(&S,*T);
while(!StackEmpty(&S)){
p=GetTop(&S);
while(GetTop(&S)) {Push(&S,p->lchild);p=GetTop(&S);} //若栈顶不为空,则将左子树一直Push进栈,再将指针变量p指向新的栈顶元素
Pop(&S); //空指针退栈
p=GetTop(&S);
if(!StackEmpty(&S)){
Pop(&S);
printf("%c",p->data);
Push(&S,p->rchild);
}
}
return OK;
}
void main(){
BiTree T=(BiTree)malloc(sizeof(BiTNode));
T->rchild=NULL;
T->data='\0'; //将头结点中的data赋空值,防止输出乱码现象
printf("先序输入二叉树:");
CreateBiTree(&(T->lchild));
printf("先序遍历输出结果:");
PrintBiTree(&T);
putchar('\n');
printf("中序遍历输出结果: ");
InOrderTraverse(&T);
putchar('\n');
}