Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,de,g,f, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Sample
Input
abc,de,g,f,
Output
3
Hint
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char pre[55];
int cnt=0;
typedef struct node
{
char data;
node *l,*r;
}Tree;
Tree* buildtree()
{
Tree *root;
if(pre[cnt]==',')
{
root=NULL;
cnt++;
}
else
{
root = new Tree;
root->data=pre[cnt++];
root->l=buildtree();
root->r=buildtree();
}
return root;
}
int leave_num(Tree *root)
{
if(!root) //如果根为空
return 0;
if(!root->l&&!root->r) //如果没有孩子,为叶子
return 1;
else
return leave_num(root->l)+leave_num(root->r);
}
int main()
{
ios::sync_with_stdio(false);
while(cin>>pre)
{
cnt=0;
Tree *root = buildtree();
cout<<leave_num(root)<<endl;
}
return 0;
}
该博客介绍了如何根据先序遍历的字符序列构建二叉树,并提供了计算二叉树中叶子节点个数的方法。通过输入一系列字符串,程序将输出每个字符串对应二叉树的叶子节点数。
606

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



