数据结构实验之二叉树三:统计叶子数
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
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<stdlib.h>
struct tree
{
char data;
struct tree*left,*right;
}*root;
char s[52];
int ans,count;
struct tree*front_create()
{
struct tree*root;//必须要有
char c=s[ans++];
if(c==',')return NULL;
else
{
root=(struct tree*)malloc(sizeof(struct tree));
root->data=c;
root->left=front_create();
root->right=front_create();
}
return root;//每次都是创造一个新的root,然后对root进行赋值,一层层的把root赋给左孩子,右孩纸,,最后赋值给总的root,一棵树就形成了
}
int searchleaf(struct tree*root)
{
if(root)
{
if(root->left==NULL&&root->right==NULL)
count++;
searchleaf(root->left);
searchleaf(root->right);
}
return count;
}
int main()
{
while(~scanf("%s",s))
{
ans=0;
count=0;
root=front_create();
printf("%d\n",searchleaf(root));
}
return 0;
}