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

来源:互联网 发布:常用编程软件有哪些 编辑:程序博客网 时间:2024/06/04 19:34

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

3

Hint

 

Author

 xam
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
char a[55];
int i,count1;
struct mode
{
    struct mode  *l,*r;
    char data;
};
struct mode *creat()
{
    struct mode *root;
    if(a[i++]==',')
        root=NULL;
    else
    {
        root=(struct mode *)malloc(sizeof(struct mode));
        root->data=a[i-1];
        root->l=creat();
        root->r=creat();
    }
    return root;
};
void leaf(struct mode *root,int &count1)//&count1表示count1要保存
{
    if(root)
    {
        if(root->l==NULL&&root->r==NULL)
        {
            count1++;
        }
        leaf(root->l,count1);
        leaf(root->r,count1);
    }
}
int main()
{
    struct mode *root;
    while(~scanf("%s",a))
    {
        i=0;
        count1=0;
        root=creat();
        leaf(root,count1);
        printf("%d\n",count1);
    }
    return 0;
}
原创粉丝点击