二叉树的先序、中序、后序操作
#include <stdio.h>
#include <malloc.h>
typedef struct Tree
{
char a;
struct Tree * LeftTree;
struct Tree * RigthTree;
}T;
T * Creat(); //生成一个二叉树
void PreShowTree(T * pT); //先序访问
void InShowTree(T * pT); //中序访问
void PostShowTree(T * pT); //后序访问
int main()
{
T * pT = Creat();
printf("先序遍历:\n");
PreShowTree(pT);
printf("中序遍历:\n");
InShowTree(pT);
printf("后序遍历:\n");
PostShowTree(pT);
return 0;
}
void PreShowTree(T * pT)
{
if( NULL != pT )
{
printf("%c\n", pT->a);
if( NULL != pT->LeftTree )
PreShowTree( pT->LeftTree );
if( NULL != pT->RigthTree )
PreShowTree( pT->RigthTree );
}
}
void InShowTree(T * pT)
{
if( NULL != pT )
{
if( NULL != pT->LeftTree)
InShowTree( pT->LeftTree );
printf("%c\n", pT->a);
if( NULL != pT->RigthTree)
InShowTree( pT->RigthTree);
}
}
void PostShowTree(T * pT)
{
if( NULL != pT )
{
if( NULL != pT->LeftTree)
PostShowTree( pT->LeftTree );
if( NULL != pT->RigthTree)
PostShowTree( pT->RigthTree);
printf("%c\n", pT->a);
}
}
T * Creat()
{
T * pA = (T *)malloc(sizeof(T));
T * pB = (T *)malloc(sizeof(T));
T * pC = (T *)malloc(sizeof(T));
T * pD = (T *)malloc(sizeof(T));
T * pE = (T *)malloc(sizeof(T));
pA->a = 'A';
pB->a = 'B';
pC->a = 'C';
pD->a = 'D';
pE->a = 'E';
pA->LeftTree = pB;
pA->RigthTree = pC;
pB->LeftTree = pB->RigthTree = NULL;
pC->LeftTree = pD;
pC->RigthTree = NULL;
pD->LeftTree = NULL;
pD->RigthTree = pE;
pE->LeftTree = pE->RigthTree = NULL;
return pA;
}