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

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

2015-11-14 21:07 411 查看

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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


示例输出

3


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node *l,*r;
};
struct node *root;
char st[51];
int cnt;
int count;

struct node *creat()
{
struct node *root;
if(st[cnt++] == ',')
root = NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root->data = st[cnt-1];
root->l = creat();
root->r = creat();
}
return root;
}

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

int main()
{
while(~scanf("%s",st))
{
cnt = 0;
count = 0;
root = creat();
jiedian(root);
printf("%d\n",count);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: