二叉树中序遍历

#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef char ElemType;
typedef struct BitNode
{
ElemType data;
BitNode *RChild,*LChild;
}BitNode,*BitTree;
typedef struct
{
BitTree base;
BitTree top;
int stacksize;
}SqStack;
int InitStack(SqStack &S)
{
S.base=(BitNode *)malloc(10*sizeof(BitNode));
if(!S.base) return FALSE;
S.top=S.base;
S.stacksize=10;
return TRUE;
}
int CreateTree(BitTree &T)
{
ElemType ch;
ch=getchar();
if(ch=='#')T=NULL;
else
{
if(!(T=(BitNode *)malloc(sizeof(BitNode))))return FALSE;
T->data=ch;
CreateTree(T->LChild);
CreateTree(T->RChild);
}
return TRUE;
}
int StackEmpty(SqStack S)
{
if(S.top==S.base)return TRUE;
return FALSE;
}
int Push(SqStack &S,BitTree e)
{
if(S.top-S.base>S.stacksize)
{
S.base=(BitNode *)realloc(S.base,(S.stacksize+10)*sizeof(BitNode));
if(!S.base)return FALSE;
S.top=S.base+S.stacksize;
S.stacksize+=10;
}
S.top = e;
++S.top;
return TRUE;
}
int Pop(SqStack &S,BitTree &e)
{
if(S.top==S.base)return FALSE;
--S.top;
e=S.top;
return TRUE;
}
int PreTraverasal(BitTree T)
{
ElemType ch;
BitTree P=T;
SqStack S;
InitStack(S);
while(P||!StackEmpty(S))
{
if(P)
{
Push(S,P);
P=P->LChild;
}
else
{
Pop(S,P);
ch=P->data;
putchar(ch);
P=P->RChild;
}
}
return TRUE;
}
int main()
{
BitTree T=NULL;
CreateTree(T);
PreTraverasal(T);
printf("\n");
return 0;
}
错在哪里?

第1个回答  2011-04-17
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef char ElemType;
typedef struct BitNode
{
ElemType data;
BitNode *RChild,*LChild;
}BitNode,*BitTree;
typedef struct
{
BitTree *base;
BitTree *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S)
{
S.base=(BitTree *)malloc(10*sizeof(BitTree));//改为BitTree,后面的一样换
if(!S.base) return FALSE;
S.top=S.base;
S.stacksize=10;
return TRUE;
}
int CreateTree(BitTree &T)
{
ElemType ch;
ch=getchar();
if(ch=='#')T=NULL;
else
{
if(!(T=(BitNode *)malloc(sizeof(BitNode))))return FALSE;
T->data=ch;
CreateTree(T->LChild);
CreateTree(T->RChild);
}
return TRUE;
}
int StackEmpty(SqStack S)
{
if(S.top==S.base)return TRUE;
return FALSE;
}
int Push(SqStack &S,BitTree e)
{
if(S.top-S.base>S.stacksize)
{
S.base=(BitTree *)realloc(S.base,(S.stacksize+10)*sizeof(BitTree));
if(!S.base)return FALSE;
// S.top=S.base+S.stacksize;
S.stacksize+=10;
}
*S.top = e;
++S.top;
return TRUE;
}
BitTree Pop(SqStack &S,BitTree e)
{
if(S.top==S.base)return FALSE;
--S.top;
e=*S.top;
return e;
}
int PreTraverasal(BitTree T)
{
ElemType ch;
BitTree P=T;
SqStack S;
InitStack(S);
while(P||!StackEmpty(S))
{
if(P)
{
Push(S,P);
P=P->LChild;
}
else
{
P=Pop(S,P);
ch=P->data;
putchar(ch);
P=P->RChild;
}
}
return TRUE;
}
int main()
{
BitTree T=NULL;
CreateTree(T);
PreTraverasal(T);
printf("\n");
return 0;
}
//运行过了,可以本回答被提问者采纳
第2个回答  2020-11-23
相似回答