输入0或1组成的字符串,如11100110001100100,用先序遍历创建一个二叉树,其中1表示结点存在,0表示结点不存在。
11100110001100100创建的二叉树如下图

二叉树创建后,求它的叶子数和深度。
#include<stdio.h>
#include<malloc.h>
typedef char DateType;
typedef struct Node{
DateType date;
struct Node*Left;
struct Node*Right;
}BiTreeNode;
//先序遍历创建二叉树
BiTreeNode*create(BiTreeNode*t)
{ char ch=getchar(); //读取一个字符
if(ch=='1')
{ t=(BiTreeNode*)malloc(sizeof(BiTreeNode));
t->date=ch; //录入数据
t->Left=create(t->Left);
t->Right=create(t->Right);
}
else
t=NULL;
return t;
}
//销毁二叉树
void Destory(BiTreeNode**t){
if((*t)!=NULL&&(*t)->Left!=NULL)
Destory(&(*t)->Left);
if((*t)!=NULL&&(*t)->Right!=NULL)
Destory(&(*t)->Right);
free(*t);
}
//先序遍历打印二叉树
void print(BiTreeNode *t){
if(t!=NULL){
printf("%c",t->date);
print(t->Left);
print(t->Right);
}
else
printf("0");
}
//先序遍历计算二叉树的叶子数
int count(BiTreeNode*t){
int sum=0;
if(t->Left!=NULL)
sum+=count(t->Left);
if (t->Right!=NULL)
sum+=count(t->Right);
if(t->Left==NULL&&t->Right==NULL)
sum++;
return sum;
}
// 先序遍历计算二叉树的深度
int depth(BiTreeNode*t){
int depth1=0,depth2=0;
if(t->Left!=NULL){
depth1+=depth(t->Left)+1;
}
if(t->Right!=NULL){
depth2+=depth(t->Right)+1;
}
return depth1>depth2?depth1:depth2;
}
int main(){
BiTreeNode*t;
t=create(t); //为什么t要重新给地址呢??
print(t);
printf("叶子数为:%d\n",count(t));
printf("深度为:%d\n",depth(t));
Destory(&t);
return 0;
}
求深度最后返回时,用到条件表达式,其意思是 如果depth1大于depth2就return depth1,否则return depth2
本文详细介绍了如何用C语言通过先序遍历构建二叉树,并提供了计算叶子数和深度的方法,涉及内存管理、递归和条件语句的应用。
694

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



