题目描述
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
输入
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
输出
输出二叉树的叶子结点个数。
示例输入
abc,,de,g,,f,,,
示例输出
3
先顺序建树;然后寻找左右子树都为空的节点(叶子),找到一个加一
源代码C++环境下可正常运行
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<malloc.h> typedef char ET; char str[100]; int i,n; typedef struct BiTNode { ET data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; int CreatrBiTree(BiTree &T) { if(i<n) { if(str[i++]==',') T=NULL; else { T=(BiTNode*)malloc(sizeof(BiTNode)); if(!T)exit(-1); T->data=str[i-1]; CreatrBiTree(T->lchild); CreatrBiTree(T->rchild); } } return 1; } void LeafCount(BiTree &T,int &count) { if(T) { if((!T->lchild)&&(!T->rchild)) { count++;//计数器 } LeafCount(T->lchild,count); LeafCount(T->rchild,count); } } int main() { BiTree T; int count; while(~scanf("%s",str)) { i=0; count=0; n=strlen(str); CreatrBiTree(T); LeafCount(T,count); printf("%d\n",count); } return 0; }