数据结构-二叉树

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值