代码:
含注释,供参考
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
struct Node*Lchild;
struct Node*Rchild;
char ch;
} BiTNode,*BiTree;
void CreateBiTree(BiTree*T);//先序创建二叉树
int Leaf(BiTree T);//统计叶子结点个数
int main()
{
BiTree BT;//二叉树
int num;//叶子结点个数
CreateBiTree(&BT);//先序创建二叉树
num=Leaf(BT);//统计叶子结点个数
printf("%d",num);
return 0;
}
/*先序创建二叉树
*T:目标二叉树
*/
void CreateBiTree(BiTree*T)
{
char c;
*T=(BiTree)malloc(sizeof(BiTNode));//分配空间
c=getchar();
if(c=='#')
{
(*T)=NULL;
}
else
{
(*T)->ch=c;
CreateBiTree(&((*T)->Lchild));先序遍历左子树
CreateBiTree(&((*T)->Rchild));//先序遍历右子树
}
}
/*统计叶子结点个数
*/
int Leaf(BiTree T)
{
int num;
if(T==NULL)
return 0;// 空,返回0
else if(T->Lchild==NULL&&T->Rchild==NULL)
return 1;//叶子结点,返回1
else
{
num=Leaf(T->Lchild)+Leaf(T->Rchild);//左右子树叶子个数之和
}
return num;
}