数据结构实验之二叉树三:统计叶子数
来源:互联网 发布:c语言内容有多少 编辑:程序博客网 时间:2024/06/09 11:34
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Example Input
abc,,de,g,,f,,,
Example Output
3
#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;typedef char telemtype;typedef struct Binode{ telemtype data; struct Binode *Lchild,*rchild;} Binode,*Bitree;char s[60];int i;Bitree creat(Bitree &T){ if(s[i++]==',') return NULL; else { T=new Binode; T->data=s[i-1]; T->Lchild=creat(T->Lchild); T->rchild=creat(T->rchild); } return T;}int countleave(Bitree T,int d){ if(T)//如果树为空,d=0(在主函数里),树不为空才进行下面操作 { if(!T->Lchild&&!T->rchild) d++; d=countleave(T->Lchild,d);//d需要一步一步的承接,不然传的是最之前的 d=countleave(T->rchild,d); } return d;}int main(){ Bitree T; while(cin>>s) { int d = 0;//叶子数 i=0; T=creat(T); d=countleave(T,d); cout<<d<<endl; } return 0;}
#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;typedef char telemtype;typedef struct Binode{ telemtype data; struct Binode *Lchild,*rchild;} Binode,*Bitree;char s[60];int i;Bitree creat(Bitree &T){ if(s[i++]==',') return NULL; else { T=new Binode; T->data=s[i-1]; T->Lchild=creat(T->Lchild); T->rchild=creat(T->rchild); } return T;}int countleave(Bitree T){ int d; if(!T) d=0; else if(!T->Lchild&&!T->rchild) d=1; else { d=countleave(T->Lchild)+countleave(T->rchild);//分别递归左子树的叶子+右子树的叶子 } return d;}int main(){ Bitree T; while(cin>>s) { i=0; T=creat(T); int d; d=countleave(T); cout<<d<<endl; } return 0;}
阅读全文
0 0
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- 数据结构实验之二叉树三:统计叶子数
- python 编码总结
- 用Constructor 2制作跑酷游戏(1 地图制作)
- Hive和HBase的整合原理
- 将十进制数对应的八进制、十六进制、十进制数输出
- 【JavaScript学习】BOM:navigator对象
- 数据结构实验之二叉树三:统计叶子数
- Java
- LDAP基础概念
- Cacti中95计费的实现
- 【POJ
- 进制转换(十转二)
- json解析
- 如何配置webpack(学习总结)
- 跨域资源共享CORS以及在zepto中使用遇到的问题