#include"stdlib.h"
#include"stdio.h"
#include"iostream.h"
//***********二叉树的遍历***********
typedef char TElemType;
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
#define OK 1
#define ERROR 0
#define OVERFLOW -2
//typedef int SElemType;
typedef int Status;
//定义二叉树及结点结构
typedef struct BiTNode
{
TElemType data;
//int IsVisit;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef BiTree SElemType;
//定义顺序栈的结构;
typedef struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//初始化一个空栈;
Status InitStack(SqStack *S)
{
(*S).base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!(*S).base)
exit(OVERFLOW);
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return OK;
}
//数据元素入栈;
Status Push(SqStack *S,SElemType e)
{
if((*S).top-(*S).base >=(*S).stacksize) //增大空间
{
(*S).base = (SElemType *)realloc((*S).base,
((*S).stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!(*S).base)
exit(OVERFLOW);
(*S).top = (*S).base+(*S).stacksize;
(*S).stacksize += STACKINCREMENT;
}
*((*S).top)++ = e;
return OK;
}
//数据元素出栈;
Status Pop(SqStack *S,SElemType *e)
{
if((*S).top == (*S).base)
return ERROR;
*e = *--(*S).top;
return OK;
}
//判断一个栈是否为空;
Status StackEmpty(SqStack S)
{
if (S.top == S.base)
return true;
else
return FALSE;
}
//销毁一个栈;
Status DestroyStack(SqStack *S)
{
free((*S).base);
(*S).base = NULL;
(*S).top = NULL;
(*S).stacksize = 0;
return OK;
}
//取栈顶的数据元素;
Status GetTop(SqStack S,SElemType *e)
{
if(S.top>S.base)
{
*e = *(S.top - 1);
return OK;
}
else
return ERROR;
}
//创建一棵空的二叉树
Status InitBiTree(BiTree *T)
{
*T = NULL;
return OK;
}
//销毁二叉树
void DestroyBiTree(BiTree *T)
{
if(*T)
{
if((*T)->lchild)
DestroyBiTree(&(*T)->lchild);
if((*T)->rchild)
DestroyBiTree(&(*T)->rchild);
free(*T);
*T = NULL;
}
}
//构造一棵二叉树
void CreateBiTree(BiTree *T)
{
TElemType ch;
InitBiTree(T);
cin>>ch;
if(ch == '0')
T = NULL;
else
*T = (BiTree)malloc(sizeof(BiTNode));
if(!(T))
return;
(*T)->data = ch;
//(*T)->IsVisit = 1;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
//输出二叉树的结点
Status visitT(TElemType e)
{
printf("%c",e);
return OK;
}
//利用栈对二叉树进行中序遍历
Status StackInOrderVisit(BiTree T,Status(*Visit)(TElemType))
{
SqStack S;
InitStack(&S);
Push(&S,T);
while(S.base != S.top)
{
//while(T->lchild && (*T).IsVisit == 1)
while(T->lchild)
{
T = T->lchild;
Push(&S,T);
//T->IsVisit = 0;
}
Pop(&S,&T);
Visit(T->data);
if(T->rchild)
{
T = T->rchild;
Push(&S,T);
}
}
return OK;
}
//主函数 CreateBiTree(&T); //线序建立二叉树 StackInOrderVisit(T,visitT); //中序遍历二叉树 printf("\n"); //运行结果: 先序创建一棵树:
void main()
{
BiTree T;
printf("先序创建一棵树:\n");
cout<<"请输入一个结点(0表示为空)"<
DestroyBiTree(&T);
}
请输入一个结点(0表示为空)
dba00c00fe00g00
abcdefg