数据结构实验之二叉树三:统计叶子数
2016-08-09 08:42
218 查看
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<algorithm>
using namespace std;
struct node
{
char data;
struct node *left;
struct node *right;
};
char a[100];
int i;
struct node *create(struct node *root)
{
char ch=a[i++];
if(ch!=',')
{
root=new node;
root->data=ch;
root->left=create(root->left);
root->right=create(root->right);
}
else root=NULL;
return root;
}
int cou=0;
int yezi(struct node *root)
{
if(root)
{
if(!root->left&&!root->right)
cou++;
yezi(root->left);
yezi(root->right);
}
return cou;
}
int main()
{
struct node*root=new node;
while(cin>>a)
{
i=0;
root=create(root);
cout<<yezi(root);
cout<<endl;
cou=0; //注意是多组输入,cou是全局变量,为避免两组输入的叶子数进行自动累加,在一组完成后,必须对cou进行清零。
}
}
数据结构实验之二叉树三:统计叶子数
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。输入
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。输出
输出二叉树的叶子结点个数。示例输入
abc,,de,g,,f,,,
示例输出
3
提示
来源
xam#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<algorithm>
using namespace std;
struct node
{
char data;
struct node *left;
struct node *right;
};
char a[100];
int i;
struct node *create(struct node *root)
{
char ch=a[i++];
if(ch!=',')
{
root=new node;
root->data=ch;
root->left=create(root->left);
root->right=create(root->right);
}
else root=NULL;
return root;
}
int cou=0;
int yezi(struct node *root)
{
if(root)
{
if(!root->left&&!root->right)
cou++;
yezi(root->left);
yezi(root->right);
}
return cou;
}
int main()
{
struct node*root=new node;
while(cin>>a)
{
i=0;
root=create(root);
cout<<yezi(root);
cout<<endl;
cou=0; //注意是多组输入,cou是全局变量,为避免两组输入的叶子数进行自动累加,在一组完成后,必须对cou进行清零。
}
}
相关文章推荐
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 3342数据结构实验之二叉树三:统计叶子数
- 3342 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- SDUT oj 数据结构实验之二叉树三:统计叶子数
- 3342 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- SDUT 3342 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数