数据结构实验之二叉树三:统计叶子数
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Example Input
abc,,de,g,,f,,,
Example Output
3
思路:明白叶子的定义就好了就是左右孩子结点为空的节点。
建树就不说了。
注意:递归找叶子的时候,因为会出现只有一个孩子结点为空的情况,所以当当前结点为空的时候别忘了返回0。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN=50+5;
char s[MAXN];
struct node
{
char key;
struct node *left,*right;
};
struct node *creat()
{
struct node *p=new node;
p->left=p->right=NULL;
return p;
};
int num;
int l;
struct node *in_build_tree(struct node *root)
{
if(s[num]==',')return 0;
if(num>=l)return 0;
root=creat();
root->key=s[num];
num++;
root->left=in_build_tree(root->left);
num++;
root->right=in_build_tree(root->right);
return root;
};
int get_leaves(struct node *root)
{
if(!root)return 0;
if(!root->left&&!root->right)return 1;
return get_leaves(root->left)+get_leaves(root->right);
}
int main()
{
while(~scanf("%s",s))
{
l=strlen(s);
num=0;
struct node *root=in_build_tree(root);
printf("%d\n",get_leaves(root));
}
return 0;
}