数据结构实验之二叉树三:统计叶子数
Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,de,g,f, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Sample
Input
abc,de,g,f,
Output
3
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int k=0;
typedef struct node
{
char data;
struct node*lchild,*rchild;
} Tree;
Tree *Create(char ch[])//建树
{
Tree *tree;
char c=ch[k++];
if(c==',')
{
return NULL;
}
else
{
tree=(Tree*)malloc(sizeof(Tree));
tree->data=c;
tree->rchild=Create(ch);
tree->lchild=Create(ch);
}
return tree;
}
int CountLeave(Tree*T)//利用递归计算叶子数
{
if(T)
{
if(!T->lchild&&!T->rchild)
{
return 1;
}
else return CountLeave(T->lchild)+CountLeave(T->rchild);
}
else return 0;
}
int main()
{
char ch[1000];
while(scanf("%s",ch)!=EOF)
{
k=0;
Tree *t=(Tree*)malloc(sizeof(Tree));
t=Create(ch);
cout<<CountLeave(t)<<endl;
}
}