C语言实现二叉树
1、 二叉树介绍
二叉树是一种分层的数据结构,其中每个节点最多有两个子节点,通常称为左子节点和右子节点。二叉树的每个节点除了包含数据外,还包含指向其左右子节点的链接
2、案例
分别用前中后序的算法遍历下面这棵树
3、二叉树实现
#include<stdio.h>
#include<malloc.h>
void createHeadTree();
void createChildTree(struct node *headTree);
void preTheTree(struct node *headTree);
void inorderTheTree(struct node *headTree);
void rearTheTree(struct node *headTree);
typedef struct node {
char data;
struct node *tleft;
struct node *tright;
}*PNode;
struct node *tree = NULL;
int main(){
createHeadTree();
createChildTree(tree);
printf("前序遍历:\n");
preTheTree(tree);
printf("\n中序遍历:\n");
inorderTheTree(tree);
printf("\n后序遍历\n");
rearTheTree(tree);
return 0;
}
void createHeadTree(){
tree = (struct node*)malloc(sizeof(struct node));
tree->data = 'A';
tree->tleft = NULL;
tree->tright = NULL;
}
void createChildTree(struct node *headTree){
PNode pb, pc, pd, pe, pf, pg, ph, pi;
pb= (PNode)malloc(sizeof(struct node));
pc = (PNode)malloc(sizeof(struct node));
pd = (PNode)malloc(sizeof(struct node));
pe = (PNode)malloc(sizeof(struct node));
pf = (PNode)malloc(sizeof(struct node));
pg = (PNode)malloc(sizeof(struct node));
ph = (PNode)malloc(sizeof(struct node));
pi = (PNode)malloc(sizeof(struct node));
pb->data = 'B';
pc->data = 'C';
pd->data = 'D';
pe->data = 'E';
pf->data = 'F';
pg->data = 'G';
ph->data = 'H';
pi->data = 'I';
headTree->tleft = pb;
headTree->tright = pc;
pb->tleft = pd;
pb->tright = pe;
pd->tleft = NULL;
pd->tright = NULL;
pe->tleft = pg;
pe->tright = NULL;
pg->tleft = NULL;
pg->tright = pi;
pi->tleft = NULL;
pi->tright = NULL;
pc->tleft = pf;
pc->tright = NULL;
pf->tleft = NULL;
pf->tright = ph;
ph->tleft = NULL;
ph->tright = NULL;
}
void preTheTree(struct node *headTree){
if (headTree){
printf("%c ", headTree->data);
preTheTree(headTree->tleft);
preTheTree(headTree->tright);
}
}
void inorderTheTree(struct node *headTree){
if (headTree){
inorderTheTree(headTree->tleft);
printf("%c ", headTree->data);
inorderTheTree(headTree->tright);
}
}
void rearTheTree(struct node *headTree){
if (headTree){
rearTheTree(headTree->tleft);
rearTheTree(headTree->tright);
printf("%c ", headTree->data);
}
}
4、遍历结果
前序遍历: A B D E G I C F H;
中序遍历: D B G I E A F H C;
后序遍历: D I G E B H FC A;