#include <stdio.h>
#include <malloc.h>
typedef struct node{
char data;
node *l_child,*r_child;
}BitNode,*BitTree;
/*建立二叉链表*/
BitTree create_bitTree(){
char ch;
scanf("%c",&ch);
BitTree T;
if(ch=='#'){
T=NULL;
}else{
T=(BitTree)malloc(sizeof(BitNode));
T->data=ch;
T->l_child=create_bitTree();
T->r_child=create_bitTree();
}
return T;//返回根节点
}
//先序遍历二叉树
void pre_order_traverse(BitTree T){
if(T!=NULL){
printf("%c",T->data);
pre_order_traverse(T->l_child);
pre_order_traverse(T->r_child);
}
//printf("\n");
}
//中序遍历二叉树
void in_order_traverse(BitTree T) {
if(T){
in_order_traverse(T->l_child);
printf("%c",T->data);
in_order_traverse(T->r_child);
}
//printf("\n");
}
//后序遍历二叉树
void post_order_traverse(BitTree T){
if(T){
post_order_traverse(T->l_child);
post_order_traverse(T->r_child);
printf("%c",T->data);
}
//
}
//计算叶子结点个数
void coutLeaf(BitTree T,int *count){
if(T){
if(T->l_child==NULL&&T->r_child==NULL){
(*count)++;
return;
}
coutLeaf(T->l_child,count);
coutLeaf(T->r_child,count);
}
}
//计算二叉树深度
int count_depth(BitTree T){
int depth=0,depth_l=0,depth_r=0;
if(!T){
depth=0;
}else{
depth_l=count_depth(T->l_child);
depth_r=count_depth(T->r_child);
depth=1+(depth_l>=depth_r?depth_l:depth_r);
}
return depth;
}
int main(){
BitTree T=create_bitTree();
printf("先序遍历二叉树为:");
pre_order_traverse(T);
printf("\n");
printf("中序遍历二叉树为:");
in_order_traverse(T);
printf("\n");
printf("后序遍历二叉树为:");
post_order_traverse(T);
printf("\n");
int count=0,depth=0;
coutLeaf(T,&count);
printf("二叉树一共:%d 枚叶子\n",count);
depth=count_depth(T);
printf("二叉树深度为:%d \n",depth);
}
C语言建立二叉数并遍历,求深度,求叶子数
最新推荐文章于 2023-02-14 20:10:15 发布