#include<stdio.h>
#include<malloc.h>
struct BTNode
{
char data;
struct BTNode * pLchild;//pLchild左孩子
struct BTNode * pRchild;//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;
}
void PreTraverseBTree(struct BTNode *pT)
{
if(pT!=NULL)
{
printf("%c\n",pT->data);
if(pT->pLchild!=NULL)
{
PreTraverseBTree(pT->pLchild);
}
if(pT->pRchild!=NULL)
{
PreTraverseBTree(pT->pRchild);
}
}
}
struct BTNode *CreateBTree(void)
{
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';// A
pB->data='B';// B C
pC->data='C';// D
pD->data='D';// E
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 InTraverseBTree(struct BTNode *pT)
{
if(pT!=NULL)
{
if(pT->pLchild!=NULL)
{
InTraverseBTree(pT->pLchild);
}
printf("%c\n",pT->data);
if(pT->pRchild!=NULL)
{
InTraverseBTree(pT->pRchild);
}
}
}
void PostTraverseBTree(struct BTNode *pT)
{
if(pT!=NULL)
{
if(pT->pLchild!=NULL)
{
PostTraverseBTree(pT->pLchild);
}
if(pT->pRchild!=NULL)
{
PostTraverseBTree(pT->pRchild);
}
printf("%c\n",pT->data);
}
}
数据结构链式二叉树的先中后序遍历
最新推荐文章于 2021-12-16 21:48:25 发布