要求
实现二叉树的创建,并输入二叉树数据
然后先序遍历输出二叉树、中序遍历输出二叉树、后序输出二叉树
输出二叉树的深度、二叉树的叶子结点
例如二叉树为:

该二叉树的先序遍历结果为:
A B D C E F
该二叉树的中序遍历结果为:
B D A E C F
该二叉树的后序遍历结果为:
D B E F C A
该二叉树的深度为:
3
该二叉树的叶子结点为:
D E F
代码实现
#include <stdio.h>
#include <malloc.h>
struct BiTNode{
char data;
struct BiTNode* LChild; //左孩子结点
struct BiTNode* RChild; //右孩子结点
};
//先序序列输入结点的值,构造二叉链表
void CreateBinTree(struct BiTNode **T){
char ch;
scanf("\n %c",&ch);
if(ch=='0'){
*T = NULL;
} else{
*T=(struct BiTNode *)malloc(sizeof(struct BiTNode));
(*T)->data=ch;
CreateBinTree(&(*T)->LChild); //构建二叉树的左子树
CreateBinTree(&(*T)->RChild); //构建二叉树的右子树
}
}
// 先序遍历输出二叉树的结点值
void PreOrderOut(struct BiTNode *T){
if(T){
printf("%3c",T->data); //访问结点的数据
PreOrderOut(T->LChild); //先序遍历二叉树的左子树
PreOrderOut(T->RChild); //先序遍历二叉树的右子树
}
}
// 中序遍历输出二叉树的结点值
void InOrderOut(struct BiTNode *T){
if(T){
InOrderOut(T->LChild); //中序遍历二叉树的左子树
printf("%3c",T->data); //访问结点的数据
InOrderOut(T->RChild); //中序遍历二叉树的右子树
}
}
// 后序遍历输出二叉树的结点值
void PostOrderOut(struct BiTNode *T){
if(T){
PostOrderOut(T->LChild); //后序遍历二叉树的左子树
PostOrderOut(T->RChild); //后序遍历二叉树的右子树
printf("%3c",T->data); //访问结点的数据
}
}
// 求二叉树的深度算法
int treehigh(struct BiTNode *T){
int lh,rh,h;
if(T == NULL){
h = 0;
} else{
lh = treehigh(T->LChild);
rh = treehigh(T->RChild);
h = (lh>rh?lh:rh)+1;
}
return h;
}
// 求二叉树的叶子结点
void inorder_leaf(struct BiTNode *T){
if(T !=NULL){
inorder_leaf(T->LChild);
if((T->LChild==NULL)&&(T->RChild==NULL)){
printf("%3c",T->data);
}
inorder_leaf(T->RChild);
}
}
int main(){
struct BiTNode *Bt;
printf("***************二叉树的输入操作***************\n");
printf("请输入二叉树数据:");
CreateBinTree(&Bt);
printf("\n***************二叉树的先序遍历***************\n");
printf("先序遍历结果:\n");
PreOrderOut(Bt);
printf("\n***************二叉树的中序遍历***************\n");
printf("中序遍历结果:\n");
InOrderOut(Bt);
printf("\n***************二叉树的后序遍历***************\n");
printf("后序遍历结果:\n");
PostOrderOut(Bt);
printf("\n***************求二叉树的深度***************\n");
int h;
h = treehigh(Bt);
printf("该二叉树的深度为:%d",h);
printf("\n***************求二叉树的叶子结点***************\n");
printf("该二叉树的叶子结点为:");
inorder_leaf(Bt);
}
输入二叉树(以先序序列输入为例)的数据:
A B 0 D 0 0 C E 0 0 F 0 0
运行结果

本文介绍了如何使用C语言实现二叉树的创建,包括先序、中序和后序遍历,以及计算二叉树的深度和叶子节点。代码示例详细展示了输入先序序列构建二叉树的过程。
2456

被折叠的 条评论
为什么被折叠?



