题目描述
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
输入
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
输出
输出二叉树的叶子结点个数。
示例输入
abc,,de,g,,f,,,
示例输出
3
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *l;
struct node *r;
}Tree;
char a[60];
int i;
int count=0;
struct node *creat(struct node *p)
{
char c;
c=a[i++];
if(c==',')
p=NULL;
else
{
p=(struct node *)malloc(sizeof(struct node));
p->data=c;
p->l=creat(p->l);
p->r=creat(p->r);
}
return p;
}
int leaves(struct node *p)
{
if(p==NULL)
return 0;
else if(p->r==NULL&&p->l==NULL)
return 1;
else
return leaves(p->r)+leaves(p->l);
}
int main()
{
struct node *p;
while(~scanf("%s",a))
{
i=0;
p = creat(p);
count=leaves(p);
printf("%d\n",count);
}
return 0;
}