一个二叉树的非第归遍历程序。错在哪里???
这个程序基本上是用C写的,但是其中使用了引用。所以就发在这个板上了。
请高手查错。最好把修改好的程序贴出来。谢谢。
#include<stdio.h>
#include<stdlib.h>
typedef struct BitNode
{
char data;
struct BitNode * lchild,* rchild;
}BitNode,*BitTree;
typedef struct
{
BitNode * base;
BitNode * top;
int stacksize;
}SqStack;
int InitStack(SqStack &S)
{
S.base=(BitNode*)malloc(100*sizeof(BitNode));
if(!S.base) exit(-1);
S.top=S.base;
S.stacksize=100;
return 1;
}
int GetTop(SqStack &S,BitNode &e)
{
if(S.top==S.base)
return -1;
e=*(S.top-1);
return 1;
}
int StackEmpty(SqStack &S)
{
if(S.top==S.base)
return 1;
else
return 0;
}
int Push(SqStack &S,BitNode &e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(BitNode*)realloc(S.base,(S.stacksize+10)*sizeof(BitNode));
if(!S.base)
exit(-1);
S.top=S.base+S.stacksize;
S.stacksize+=10;
}
*S.top=e;
S.top++;
return 1;
}
int Pop(SqStack &S,BitNode &e)
{
if(S.top==S.base)
return -1;
e=*(--S.top);
return 1;
}
int CreateBitTree(BitTree &T)
{
char ch;
scanf("%c",&ch);
if(ch==' ')
T=NULL;
else
{
if(!(T=(BitNode*)malloc(sizeof(BitNode))))
exit(-1);
T->data=ch;
CreateBitTree(T->lchild);
CreateBitTree(T->rchild);
}
return 1;
}
int InOrderTraverse(BitTree &T,int (*Visit)(int e))
{
BitNode p;
SqStack S;
InitStack(S);
Push(S,*T);
while(!StackEmpty(S))
{
while(GetTop(S,p)&&(p.data!=NULL))
Push(S,*(p.lchild));
Pop(S,p);
if(!StackEmpty(S))
{
Pop(S,p);
if(!Visit(p.data))
return -1;
Push(S,*(p.rchild));
}
}
return 1;
}
int PrintElement(int e)
{
printf("%d",e);
return 1;
}
void main()
{
BitTree T;
CreateBitTree(T);
InOrderTraverse(T,PrintElement);
}