#include
#include
#define NULL 0
struct BTNode
{
char data;
struct BTNode * pLchild;//p是指针,L为左,chlid为孩子
struct BTNode * pRchild;
};
//struct BTNode * CreateBTree(void);
//void PreTraverseBTree(struct BTNode * pT)
//先序遍历
void PreTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
printf("%c\n",pT->data);
// PreTraverseBTree(pT->pLchild);
// PreTraverseBTree(pT->pRchild);
if(pT->pLchild != NULL )
{
PreTraverseBTree(pT->pLchild);
}
if(pT->pRchild != NULL )
{
PreTraverseBTree(pT->pRchild);
}
}
//pT->可以代表整个左子树
/* 伪算法
先访问根节点
再先序访问左子树
再先序访问右子树*/
}
//中序遍历
void InTraerseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
// PreTraverseBTree(pT->pLchild);
// PreTraverseBTree(pT->pRchild);
if(pT->pLchild != NULL )
{
InTraerseBTree(pT->pLchild);
}
printf("%c\n",pT->data);
if(pT->pRchild != NULL )
{
InTraerseBTree(pT->pRchild);
}
}
//pT->可以代表整个左子树
/* 伪算法
访问左子树
再访问根节点
再先序访问右子树*/
}
//后序遍历
void PostTraverseBTree(struct BTNode * pT)
{
if (pT != NULL)
{
// PreTraverseBTree(pT->pLchild);
// PreTraverseBTree(pT->pRchild);
if(pT->pLchild != NULL )
{
PostTraverseBTree(pT->pLchild);
}
if(pT->pRchild != NULL )
{
PostTraverseBTree(pT->pRchild);
}
printf("%c\n",pT->data);
}
//pT->可以代表整个左子树
/* 伪算法
先访问左子树
再先序访问右子树
再先序访问根节点*/
}
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';
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;
}
int main(void)
{
struct BTNode * pT =CreateBTree();
printf("先序遍历输出:\n");
PreTraverseBTree(pT);
printf("中序遍历输出:\n");
InTraerseBTree(pT);
printf("后序遍历输出:\n");
PostTraverseBTree(pT);
return 0;
}
阅读(1116) | 评论(0) | 转发(2) |