您的位置:首页 > 理论基础 > 数据结构算法

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

2016-08-09 08:42 218 查看


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


Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

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


示例输出

3


提示

 

来源

 xam

#include<stdio.h>

#include<iostream>

#include<stdlib.h>

#include<algorithm>

using namespace std;

struct node

{

    char data;

    struct node *left;

    struct node *right;

};

char a[100];

int i;

struct node *create(struct node *root)

{

    char ch=a[i++];

    if(ch!=',')

    {

        root=new node;

        root->data=ch;

        root->left=create(root->left);

        root->right=create(root->right);

    }

    else root=NULL;

    return root;

}

int cou=0;

int yezi(struct node *root)

{

    if(root)

    {

        if(!root->left&&!root->right)
            cou++;

           yezi(root->left);

            yezi(root->right);

       
    }

    return cou;

}

int main()

{

    struct node*root=new node;

    while(cin>>a)

    {

        i=0;

        root=create(root);

        cout<<yezi(root);

        cout<<endl;

        cou=0;          //注意是多组输入,cou是全局变量,为避免两组输入的叶子数进行自动累加,在一组完成后,必须对cou进行清零。

    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: