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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43545471/article/details/102623709

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>

char str[100];
int k = 0;
int count = 0;

typedef struct TreeNode
{
    char data;
    struct TreeNode* Lsubtree;
    struct TreeNode* Rsubtree;
}Tree;

Tree* CreateTree(Tree *T)
{
    char ch = str[k++];
    if (ch == ',')
    {
        T = NULL;
    }
    else
    {
        T = (Tree*)malloc(sizeof(Tree));
        T->data = ch;
        T->Lsubtree = CreateTree(T->Lsubtree);
        T->Rsubtree = CreateTree(T->Rsubtree);
        if (T->Lsubtree == NULL&&T->Rsubtree == NULL) // 若左右子树为空,则该节点为叶子
        {
            count++;
        }
    }
    return T;
}


int main()
{
    Tree* T;
    while(scanf("%s",&str)!=EOF)
    {
        k = 0; // 重置索引
        count = 0; // 重置计数变量
        T = CreateTree(T);
        printf("%d\n", count);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43545471/article/details/102623709