数据结构实验之二叉树三:统计叶子数
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 <bits/stdc++.h>
using namespace std;
char str[51];
int i, cnt;
struct bitree
{
char data;
struct bitree *lc;
struct bitree *rc;
};
bitree *create()
{
bitree *tree;
if(str[++i]==',')
tree = NULL;
else
{
tree = new bitree;
tree->data = str[i];
tree->lc = create();
tree->rc = create();
}
return tree;
}
int countleaf(bitree *tree)
{
if(tree)
{
if((!tree->lc)&&(!tree->rc))
cnt++;
countleaf(tree->lc);
countleaf(tree->rc);
}
return cnt;
}
int main()
{
bitree *tree;
while(gets(str))
{
i = -1;
cnt = 0;
tree = create();
cout<<countleaf(tree)<<endl;
}
return 0;
}

本文介绍了一种通过先序遍历字符序列构建二叉树,并计算其叶子节点数量的方法。采用C++实现,输入为包含字符和逗号(表示空节点)的字符串,输出为叶子节点的数量。

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



