【求调试找错】先序遍历的递归算法和中序遍历二叉树的非递归算法的C语言实现(总是程序停止运行)
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW 1
#define OK 0
#define ERROR 1
typedef struct BiTNode{
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct{
BiTree *base;
BiTree *top;
int stacksize;
}SqStack;
void InitBiTree(BiTree &T){
T=NULL;
}
int CreateBiTree(BiTree &T){
int c;
scanf("%d",&c);
if(c==0) T=NULL;
else{
if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))
exit(OVERFLOW);
T->data=c;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int printelemt(int e){
printf("%d",e);
return OK;
}
int PreorderTraverse(BiTree T,int(*visit)(int e)){
if(T){
visit(T->data);
PreorderTraverse(T->lchild,visit);
PreorderTraverse(T->rchild,visit);
}
}
int InitStack(SqStack &S){
S.base=(BiTree*)malloc(STACK_INIT_SIZE*sizeof(BiTree));
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
int Push(SqStack &S,BiTree e){
if(S.top-S.base>=S.stacksize){
S.base=(BiTree*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(BiTree));
if(!S.base)
printf("OVERFLOW");
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
}
int Pop(SqStack &S,BiTree &e){
if(S.top == S.base)
return ERROR;
e =*--S.top;
return OK;
}
int StackEmpty(SqStack &S)
{
if(S.top == S.base)
return OK;
else
return ERROR;
}
int InorderTraverse(BiTree T,int(*visit)(int e)){
SqStack S;
InitStack(S);
BiTree P=T;
while(P||!StackEmpty(S)){
SqStack S;
InitStack(S);
BiTree p;
p = T;
while(p || !StackEmpty(S)) {
if(p) {
Push(S,P);
P= P->lchild;
}
else{
Pop(S,P);
if(!visit(P->data)) return ERROR;
P = P->rchild;
}
}
}
return OK;}
int main()
{
BiTree T;
InitBiTree(T);
CreateBiTree(T);
PreorderTraverse(T,printelemt);
printf("\n");
InorderTraverse(T,printelemt);
}