include <stdio.h>
include <malloc.h>
struct BTNode
{
char data;
struct BTNode * pLchild; // p是指针 L是左 child是孩子
struct BTNode * pRchild;
};
struct BTNode * createBTree()
{
struct BTNode * pA = (struct BTNode *)malloc(sizeof(struct BTNode));
struct BTNode * pB = (struct BTNode *)malloc(sizeof(struct BTNode));
struct BTNode * pC = (struct BTNode *)malloc(sizeof(struct BTNode));
struct BTNode * pD = (struct BTNode *)malloc(sizeof(struct BTNode));
struct BTNode * pE = (struct BTNode *)malloc(sizeof(struct BTNode));
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pA->pLchild = pB;
pA->pRchild = pC;
pB->pLchild = pB->pRchild = NULL;
pC->pLchild = pD;
pC->pRchild = NULL;
pD->pLchild = NULL;
pD->pRchild = pE;
pE->pLchild = pE->pRchild = NULL;
return pA;
}
void PreTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
printf("%c ", pT->data);
if (NULL != pT->pLchild)
PreTraverseBTree(pT->pLchild);
if (NULL != pT->pRchild)
PreTraverseBTree(pT->pRchild);
}
}
void InTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
if (NULL != pT->pLchild)
InTraverseBTree(pT->pLchild);
printf("%c ", pT->data);
if (NULL != pT->pRchild)
InTraverseBTree(pT->pRchild);
}
}
void PostTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
if (NULL != pT->pLchild)
InTraverseBTree(pT->pLchild);
if (NULL != pT->pRchild)
InTraverseBTree(pT->pRchild);
printf("%c ", pT->data);
}
}
int main()
{
struct BTNode * pT = createBTree(); // 二叉树造好
printf("先序遍历的结果是:");
PreTraverseBTree(pT);
printf("\n");
printf("中序遍历的结果是:");
InTraverseBTree(pT);
printf("\n");
printf("后序遍历的结果是:");
PostTraverseBTree(pT);
printf("\n");
return 0;
}