数据结构实验之二叉树三:统计叶子数
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Sample Input
abc,,de,g,,f,,,
Sample Output
3
Hint
Source
xam
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef struct st
{
struct st *l,*r;
char data;
} tree;
char s[52];
int t,sum;
tree *creat(tree *root)
{
if(s[++t]==',')
root=NULL;
else
{
root=new tree;
root->data=s[t];
root->l=creat(root->l);
root->r=creat(root->r);
}
return root;
}
void yue(tree *root)
{
if(root)
{
if(root->r==NULL&&root->l==NULL)
{
sum++;
}
yue(root->l);
yue(root->r);
}
}
int main()
{
while(scanf("%s",s)!=EOF)
{
t=-1;
sum=0;
tree *root;
root=creat(root);
yue(root);
printf("%d\n",sum);
}
return 0;
}
本文介绍了一种通过先序遍历字符序列构建二叉树,并计算其叶子节点数量的方法。利用递归创建二叉树结构,再通过深度优先搜索统计叶子节点,最后输出结果。适用于数据结构和算法学习。
947

被折叠的 条评论
为什么被折叠?



