暑假集训day7——数据结构实验之二叉树三:统计叶子数

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

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

Sample Input

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

Sample Output

3

Hint

 

Source

xam

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char s[100];
int top, ans;

struct node
{
    char data;
    struct node *l, *r;

}*root;

struct node *creat()
{
    struct node *root;//注意这里每次进入之后都会重新拥有一个根节点

    if(s[++top] == ',')
    {
        root = NULL;
    }

    else
    {
        root = (struct node *)malloc(sizeof(struct node));
        root-> data = s[top];

        root-> l = creat();
        root-> r = creat();
    }

    return root;
}

int jiedian(struct node *root)
{
    if(root != NULL)
    {
        if(root-> l == NULL && root-> r == NULL)
        {
            ans++;
        }

        else
        {
            jiedian(root-> l);   //然后在找左子树
            jiedian(root-> r);   //然后再找右子树
        }
    }
 
    return ans;  //递归

}

int main(void)
{
    while(gets(s) != NULL)
    {
        top = -1;
        ans = 0;

        root = creat(); //先建立好二叉树

        jiedian(root);  //再找叶子

        printf("%d\n", ans);
    }

    return 0;
}



猜你喜欢

转载自blog.csdn.net/Eider1998/article/details/81476549
今日推荐