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

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

Description

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

Input

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

Output

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

Sample

Input 

abc,,de,g,,f,,,

Output 

3

Hint

#include <stdio.h>
#include <stdlib.h>
 
typedef struct node
{
    char data;
    struct node *lchild,*rchild;
}node,*nodeptr;
 
char a[55];
int i,count;
 
struct node *Creat(struct node *T)
{
    T=(struct node *)malloc(sizeof(struct node));
    if(a[i++]==',')T=NULL;
    else
    {
        T->data=a[i-1];
        T->lchild=Creat(T->lchild);
        T->rchild=Creat(T->rchild);
 
    }
    return T;
}
 
int Countleaf(struct node *T)
{
    if(T)
    {
        if((!T->rchild)&&(!T->lchild))
        {//判断是否是叶子节点,利用叶子节点的特点
            count++;
        }
        Countleaf(T->lchild);
        Countleaf(T->rchild);
    }
    return count;
}
 
 
int main()
{
    struct node *T;
    while(~scanf("%s",a))
    {
        T=Creat(T);
        count=0;
        i=0;
        printf("%d
",Countleaf(T));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12703453.html