统计叶节点

来源:互联网 发布:罗技g502 mac 编辑:程序博客网 时间:2024/04/28 06:12

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

3




#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
char q[100];int i,count;
struct node
{
    char data;
    struct node *l,*r;
};
struct node *creat(struct node *p)
{


    if(q[i++]==',')
     p=NULL;
    else
    {
        p=(struct node *)malloc(sizeof(struct node));
        p->data=q[i-1];
        p->l=creat(p->l);
        p->r=creat(p->r);
    }
    return p;
}
void CountLeaf(struct node *p,int &count){
if(p){
if((!p->l)&&(!p->r))
count++;
CountLeaf(p->l,count);
CountLeaf(p->r,count);
}
}
int main()
{


   while(scanf("%s",q)!=EOF)
    {i=0;count=0;
        struct node *head;
        head = (struct node *)malloc(sizeof(struct node));
        head = creat(head);
     CountLeaf(head,count);
     printf("%d\n",count);
    }
    return 0;
}

0 0
原创粉丝点击