用C的递归算法求树的叶子数
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
char data;
struct node *lchild,*rchild;
}NODE;
NODE * create_tree()
{
NODE *t;
char c;
scanf("%c",&c);
if(c==32)
return t=0;
else
{
t=(NODE *)malloc(sizeof(NODE));
t->data=c;
t->lchild=create_tree();
t->rchild=create_tree();
return t;
}
}
//求树的高度
int length(NODE *t)
{
int m,n;
if(t==NULL)
return 0;
else
{
m=length(t->lchild);
n=length(t->rchild);
return m>n?m+1:n+1;
}
}
//求树的叶子数
int count_leaf(NODE *t)
{
int count=0,m=0,n=0;
if(t)
{
if(t->lchild==NULL&&t->rchild==NULL)
{
m=count_leaf(t->lchild);
n=count_leaf(t->rchild);
return m+n+1;
}
}
}
void main()
{
NODE *t;
printf("请输入各个节点的值:\n");
t=create_tree();
printf("树的高度为:");
printf("%d\n",length(t));
printf("树的叶子数为:");
printf("%d",count_leaf(t));
printf("\n");
}
部分代码我以写出,就是叶子数不知道怎么求,急求解
[解决办法]
左右孩子为NULL就是叶子啊