您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树三:统计叶子数

2015-11-27 21:28 453 查看
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

int cnt;
char s[101];
struct node
{
char data;
struct node *rchild;
struct node *lchild;
};
struct node *buildtree()
{
struct node *root;
if(s[cnt++]==',' )root=NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=s[cnt-1];
root->rchild=buildtree();
root->lchild=buildtree();

}
return root;

};
int LeafCount (node *root)
{
if(root==NULL)
return 0;
else
{
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
return LeafCount(root->lchild)+LeafCount(root->rchild);
}
}
int main()
{
while(cin>>s)
{
struct node *root;
cnt=0;
root=buildtree();
cout<<LeafCount(root)<<endl;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: