小编存储了不少代码,最近新开通了CSDN博客,以前一直看到别人的代码分享,深受启发,非常感谢,所以小编现在也要将自己的代码分享给大家,希望大家可以与潇小白一起在编程的道路上越走越远,早日成为大佬!虽然我目前只是一名大二的学生,不过我会努力哒!加油!
本次分享的用C语言求二叉树叶子节点的个数,由于代码比较简单,潇小白本次就设置了一个C文件,不是以前的工程文件,小伙伴们运行时要注意哦!
代码如下:
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
typedef char ElemType;
typedef struct node
{
ElemType data; //数据元素
struct node *lchild; //指向左孩子
struct node *rchild; //指向右孩子
}*BitTree;
void CreatBiTree(BitTree *bt)
{
char ch;
ch=getchar();
if(ch=='#')
*bt=NULL;
else
{
*bt=(BitTree)malloc(sizeof(BitTree));
(*bt)->data=ch;
CreatBiTree(&((*bt)->lchild));
CreatBiTree(&((*bt)->rchild));
}
}
int CountLeaf(BitTree *bt,int count)
{
if((*bt)!=NULL)
{
if((*bt)->lchild==NULL&&(*bt)->rchild==NULL)
count++;
count=CountLeaf(&(*bt)->lchild,count);
count=CountLeaf(&(*bt)->rchild,count);
}
return count;
}
void main()
{
int count=0;
BitTree tree;
printf("请输入二叉树(以#为空子树):");
CreatBiTree(&tree);
count=CountLeaf(&tree,count);
printf("叶子节点数为:%d",count);
printf("\n");
}
运行结果看这里: