数据结构实验之二叉树三:统计叶子数
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;
}