64,637
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
#define OVERFLOW -1
typedef char SElemType;
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct{
BiTNode *base;
BiTNode *top;
int stacksize;
}SqStack;
int CreateBiTree(BiTree &T){//不明白BiTree &T到底表示什么意思,只是我写BiTNode *T就是不行,当然下面改成BiTNode T和&T
char ch;
scanf("%c",&ch);
if(ch=='#')T=NULL;
else{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))exit(OVERFLOW);
T->data=ch;
if(T->lchild!=NULL||T->rchild!=NULL){
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
return OK;
}
int InitStack(SqStack *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;
}
bool StackEmpty(SqStack *S){
if(S->top==S->base)
return true;
else
return false;
}
bool Visit(char data){
if(data!=NULL)
return true;
else
return false;
}
BiTNode *GetTop(SqStack *S){
BiTNode *e;
if(S->top==S->base) return NULL;
e=(S->top-1);
// printf("the top element is %c\n",e);
return e;
}
int Push(SqStack *S,BiTree &T){
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;
S->top++;
return OK;
}
void Pop(SqStack *S){
if(S->top==S->base) printf("ERROR!!!");
--S->top;
}
int InOrderTraverse(BiTree &T){
SqStack S;
InitStack(&S);
Push(&S,T);
while(!StackEmpty(&S)){
BiTNode *p;
p=GetTop(&S);
while(p) Push(&S,p->lchild);
Pop(&S);
if(!StackEmpty(&S)){
Pop(&S);
if(!Visit(p->data)) return ERROR;
Push(&S,p->rchild);
}
}
return OK;
}
void main(){
BiTree T;
CreateBiTree(T);
InOrderTraverse(T);
}