Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,de,g,f, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Sample Input
abc,de,g,f,
Sample Output
3
Hint
Source
xam
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct tree
{
struct tree *left,*right;
char data;
};
int i;
char a[55];
struct tree *creat()
{
struct tree *t;
if(a[i]==',')
{
i++;
t=NULL;
}
else
{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=a[i];
i++;
t->left=creat();
t->right=creat();
}
return t;
}
int count(struct tree *t)
{
if(t==NULL)return 0;
if(t->left==NULL&&t->right==NULL)
return 1;
else return count(t->left)+count(t->right);
}
int main()
{
struct tree* root;
int re;
while(~scanf("%s",a))
{
i=0;
root=creat();
re=count(root);
printf("%d\n",re);
}
return 0;
}