您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树三:统计叶子数

2016-10-25 20:07 190 查看

数据结构实验之二叉树三:统计叶子数

Time Limit: 1000MS Memory Limit: 65536KB
[align=center]Submit Statistic[/align]

Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。

Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。

Output

输出二叉树的叶子结点个数。

Example Input

abc,,de,g,,f,,,


Example Output

3

#include<stdio.h>
struct node
{
int data;
struct node *left,*right;
};
char s[110];
int cnt;
int num;
struct node *creat()
{
struct node *t;
if(s[++cnt]==',')
{
t=NULL;
}
else
{
t=new node;
t->data=s[cnt];
t->left=creat();
t->right=creat();
}
return t;
};
void in(struct node *t)
{
if(t)
{
in(t->left);
printf("%c",t->data);
in(t->right);
}
}
void leave(struct node *root)
{

if(root)
{

if(root->left==NULL&&root->right==NULL)
{
num++;
}
leave(root->left);
leave(root->right);
}
}
int main()
{
while(~scanf("%s",s))
{
cnt=-1;
num=0;
struct node *root;
root=creat();

leave(root);
printf("%d\n",num);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: