二叉树先序遍历和中序遍历
#include <stdlib.h>
#include <stdio.h>
#define STACK_INIT_SIZE 10
#define LIST_INIT_SIZE 100
#define STACKINCREMENT 10
#define DEBUG 1
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int TElemType,SElemType;
typedef int Status;
typedef struct BiTNode{
TElemType data;
struct BiTNode
*lchild,*rchild;
}BiTNode,*BiTree;
typedef BiTree SElemType_Sq;
Status PrintElement(TElemType e)
{
printf("%c ",e);
return OK;
}
typedef struct{
SElemType_Sq *base;
SElemType_Sq *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base=(SElemType_Sq *)malloc(STACK_INIT_SIZE*sizeof(SElemType_Sq));
if(!S->base) exit(OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
Status GetTop(SqStack *S,SElemType_Sq *e)
{
if(S->top==S->base) return ERROR;
*e=*(S->top-1);
return OK;
}
Status Push(SqStack *S,SElemType_Sq e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(SElemType_Sq *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(SElemType_Sq));
if(!S->base) exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top++=e;
return OK;
}
Status Pop(SqStack *S,SElemType_Sq *e)
{
if(S->top==S->base) return ERROR;
*e=*--S->top;
return OK;
}
Status StackEmpty(SqStack *S)
{
if(S->top==S->base) return 1;
return 0;
}
Status PreOrderTraverse(BiTree T,Status(*Visit)(TElemType e))
{
if(T){
if(Visit(T->data))
if(PreOrderTraverse(T->lchild,Visit))
if(PreOrderTraverse(T->rchild,Visit))
return OK;
return ERROR;
}
else
return OK;
}
Status CreateBiTree(BiTree *T)
{
char ch;
scanf("%c",&ch);
if(ch=='#') *T=NULL;
else
{
if(!(*T=(BiTNode *)
malloc(sizeof(BiTNode))))
exit(OVERFLOW);
(*T)->data=ch;
CreateBiTree(&((*T)->lchild));
CreateBiTree(&((*T)->rchild));
}
return OK;
}
Status InOrderTraverse(BiTree T ,Status(Visit)(TElemType e))
{
SqStack S; BiTree p;
InitStack(&S);
Push(&S,T);
while (!StackEmpty(&S))
{
while(GetTop(&S,&p)&&p) Push(&S,p->lchild);
Pop(&S,&p);
if(!StackEmpty(&S))
{
Pop(&S,&p);
if(!Visit(p->data))
return ERROR;
Push(&S,p->rchild);
}
}
return OK;
}
int main()
{
SqStack stack1;
BiTree tree1;
InitStack(&stack1);
CreateBiTree(&tree1);
PreOrderTraverse(tree1,PrintElement);
printf("\n");
InOrderTraverse(tree1,PrintElement);
system("pause");
return 0;
}