如果把二叉树的建立中的递归理解透彻了,那么这个题目就非常简单了,只需要加上一个判断条件和一个计数变量即可;
题目如上:
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *lchild,*rchild;
}node,*nodeptr;
char a[55];
int i,count;
struct node *Creat(struct node *T)
{
T=(struct node *)malloc(sizeof(struct node));
if(a[i++]==',')T=NULL;
else
{
T->data=a[i-1];
T->lchild=Creat(T->lchild);
T->rchild=Creat(T->rchild);
}
return T;
}
int Countleaf(struct node *T)
{
if(T)
{
if((!T->rchild)&&(!T->lchild))
{//判断是否是叶子节点,利用叶子节点的特点
count++;
}
Countleaf(T->lchild);
Countleaf(T->rchild);
}
return count;
}
int main()
{
struct node *T;
while(~scanf("%s",a))
{
T=Creat(T);
count=0;
i=0;
printf("%d\n",Countleaf(T));
}
return 0;
}
对这个代码不是很理解的可以先理解一下上面这一个二叉树遍历的递归过程,关联的文章