http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=3342&cid=1794
数据结构实验之二叉树三:统计叶子数
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
输入
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
输出
输出二叉树的叶子结点个数。
示例输入
abc,,de,g,,f,,,
示例输出
3
#include <stdio.h>
#include <stdlib.h>
typedef char type;
typedef struct tnode
{
type data;
tnode *lc;
tnode *rc;
}tnode,*tree;
int leaf=0,i=0;
type s[60];
tree creat(tree &T)
{
if(s[i]==',')
{
T=NULL;
i++;
}
else
{
T=(tree)malloc(sizeof(tnode));
T->data=s[i];
i++;
T->lc=creat(T->lc);
T->rc=creat(T->rc);
}
return T;
}
void countleaf(tree T)
{
if(T)
{
if(T->lc==NULL&&T->rc==NULL)
leaf++;
else
{
countleaf(T->lc);
countleaf(T->rc);
}
}
}
int main()
{
tree T;
while(gets(s)!=NULL)
{
i=0;
T=creat(T);
leaf=0;
countleaf(T);
printf("%d\n",leaf);
}
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-1262207.html