自己学习数据结构的编程练习;
平台:MacOS Catalina
软件:Xcode
时间:10.2 mins
这棵树的结构为:
#include <stdio.h>
#include <malloc.h>
typedef struct BiTree
{
char data;
struct BiTree * pLBiTree;
struct BiTree * pRBiTree;
}BiTree, *pBiTree;
pBiTree create_BiTree(void);
void Create_BinTree(pBiTree T);
void pre_traserse(pBiTree pB);
void middle_traserse(pBiTree pB);
void post_traserse(pBiTree pB);
int main(void)
{
pBiTree BTree;
BTree = create_BiTree();
pre_traserse(BTree);
printf("\n");
middle_traserse(BTree);
printf("\n");
post_traserse(BTree);
printf("\n");
return 0;
}
//静态建立的,还可以使用动态建立(递归)
pBiTree create_BiTree(void)
{
pBiTree pA = (pBiTree)malloc(sizeof(BiTree));
pBiTree pB = (pBiTree)malloc(sizeof(BiTree));
pBiTree pC = (pBiTree)malloc(sizeof(BiTree));
pBiTree pD = (pBiTree)malloc(sizeof(BiTree));
pBiTree pE = (pBiTree)malloc(sizeof(BiTree));
pBiTree pF = (pBiTree)malloc(sizeof(BiTree));
pBiTree pG = (pBiTree)malloc(sizeof(BiTree));
pA->data = 'A';
pB->data = 'B';
pC->data = 'C';
pD->data = 'D';
pE->data = 'E';
pF->data = 'F';
pG->data = 'G';
pA->pLBiTree = pB;
pA->pRBiTree = pC;
pB->pLBiTree = pD;
pC->pLBiTree = pE;
pC->pRBiTree = pF;
pF->pLBiTree = pG;
pB->pRBiTree = NULL;
pD->pLBiTree = pD->pRBiTree = NULL;
pE->pLBiTree = pE->pRBiTree = NULL;
pG->pLBiTree = pG->pRBiTree = NULL;
pF->pRBiTree = NULL;
return pA;
}
//动态创建二叉树,输入:ABC##DE##F##GH##
void create_front_tree(Binary_tree *p)
{
char ch;
printf("input: ");
scanf("%c\n", &ch);
if(ch == '#')
{
*p = NULL; //代替NULL
return ;
}
else
{
*p = (Binary_tree) malloc(sizeof(TreeNode));
if(!*p)
{
exit(-1); //空间申请失败
}
(*p)->data = ch;
create_front_tree(&((*p)->left_child));
create_front_tree(&((*p)->right_child));
}
}
void pre_traserse(pBiTree pB)
{
if(NULL != pB)
{
printf("%c ",pB->data);
if(NULL != pB->pLBiTree)
pre_traserse(pB->pLBiTree);
if(NULL != pB->pRBiTree)
pre_traserse(pB->pRBiTree);
}
}
void middle_traserse(pBiTree pB)
{
if(NULL != pB)
{
if(NULL != pB->pLBiTree)
middle_traserse(pB->pLBiTree);
printf("%c ",pB->data);
if(NULL != pB->pRBiTree)
middle_traserse(pB->pRBiTree);
}
}
void post_traserse(pBiTree pB)
{
if(NULL != pB)
{
if(NULL != pB->pLBiTree)
post_traserse(pB->pLBiTree);
if(NULL != pB->pRBiTree)
post_traserse(pB->pRBiTree);
printf("%c ",pB->data);
}
}
测试结果
A B D C E F G
D B A E C G F
D B E G F C A
Press any key to continue