# include
# include
struct BTNode
{
int data;
struct BTNode * pLchild;//p是指针,L是左,child是孩子
struct BTNode * pRchild;
};
//函数声明
struct BTNode * CreateBTree(void);//创建树
void PreTraverseBTree(struct BTNode * pT);//先序遍历
void InTraverseBTree(struct BTNode * pT);//中序遍历
void PostTraverseBTree(struct BTNode * pT);//后续遍历
int main(void)
{
struct BTNode * pT = CreateBTree();
PreTraverseBTree(pT);
printf("\n");
InTraverseBTree(pT);
printf("\n");
PostTraverseBTree(pT);
return 0;
}
//创建树
struct BTNode * CreateBTree(void)
{
struct BTNode * pA = (struct BTNode * )malloc(sizeof(BTNode));
struct BTNode * pB = (struct BTNode * )malloc(sizeof(BTNode));
struct BTNode * pC = (struct BTNode * )malloc(sizeof(BTNode));
struct BTNode * pD = (struct BTNode * )malloc(sizeof(BTNode));
struct BTNode * pE = (struct BTNode * )malloc(sizeof(BTNode));
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pA->pLchild = pB;
pA->pRchild = pC;
pB->pLchild = NULL;
pB->pRchild = NULL;
pC->pLchild = pD;
pC->pRchild = NULL;
pD->pLchild = NULL;
pD->pRchild = pE;
pE->pLchild = NULL;
pE->pRchild = NULL;
return pA;
}
//先序遍历
void PreTraverseBTree(struct BTNode * pT)
{ //先访问根节点,再先序访问左子树,最后先序访问右子树
if ( pT != NULL)
{
printf("%c\n",pT->data);//访问根节点
//pT->pLchild可以代表整个左子树
PreTraverseBTree(pT->pLchild);
PreTraverseBTree(pT->pRchild);
}
return;
}
//中序遍历
void InTraverseBTree(struct BTNode * pT)
{
if(pT != NULL )
{
if (NULL != pT->pLchild)
{
InTraverseBTree(pT->pLchild);
}
printf("%c\n",pT->data);
if (NULL != pT->pRchild)
{
InTraverseBTree(pT->pRchild);
}
}
return;
}
//后续遍历
void PostTraverseBTree(struct BTNode * pT)
{
if(pT != NULL )
{
if (NULL != pT->pLchild)
{
PostTraverseBTree(pT->pLchild);
}
if (NULL != pT->pRchild)
{
PostTraverseBTree(pT->pRchild);
}
printf("%c\n",pT->data);
}
return;
}
|