G - 数据结构实验之二叉树三:统计叶子数

Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,de,g,f, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output

输出二叉树的叶子结点个数。
Sample

Input

abc,de,g,f,
Output

3

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<malloc.h>
typedef struct node
{
    struct node *l,*r;
    char data;
} node,*Tree;
char s[1100],ch;
int k;
void creat(Tree&T)
{
    ch = s[k++];
    if(ch == ',')
        T =  NULL;
    else
    {
        T = (struct node*)malloc(sizeof(node));
        T ->data = ch;
        creat(T->l);
        creat(T->r);
    }
}
/*int Deep(Tree&T)
{
    int d = 0;
    if(T)
    {
        int ld = Deep(T->l);
        int rd = Deep(T->r);
        if(ld>rd)
            d =ld+1;
        else
            d = rd+1;
    }
    return d;
}*/
void Countleaf(Tree T,int &cnt)
{
    if(T)
    {
        if(T->l==NULL&&T->r==NULL)
            cnt++;
        Countleaf(T->l,cnt);
        Countleaf(T->r,cnt);
    }
}
int main()
{
    Tree T;
    int x;
    while(gets(s))
    {
        k = 0;
        x = 0;
        creat(T);
        Countleaf(T,x);
        printf("%d\n",x);
    }


    return 0;
}

发布了177 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Fusheng_Yizhao/article/details/104868206