如何统计二叉树中的叶子节点数量?
- 内容介绍
- 文章标签
- 相关推荐
本文共计416个文字,预计阅读时间需要2分钟。
数据结构实验之二叉树三:统计叶子节点数 + 时间限制:1000 ms + 内存限制:65536 KiB + 提交统计问题描述:已知二叉树的一个按先序遍历的输入序列,如abc, de, g, f, (其中,表示空节点)。请编写程序统计二叉树中叶子节点的数量。
数据结构实验之二叉树三:统计叶子数
Time Limit:1000 msMemory Limit:65536 KiB
SubmitStatistic
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 <stdlib.h>
#include <string.h>
char a[101];
int l;
struct node//二叉树的定义
{
char data;
struct node *lc;
struct node *rc;
};
struct node *creat()
{
struct node *root;
char c;
c = a[l++];
if(c == ',')
{
return NULL;
}
else
{
root = (struct node *)malloc(sizeof(struct node));
root->data = c;
root->lc = creat();
root->rc = creat();
}
return root;
}
int leave(struct node *root)
{
if(root == NULL)
{
return 0;
}
if(root->lc == NULL && root->rc == NULL)
{
return 1;
}
else
return leave(root->lc) + leave(root->rc);
}
int main()
{
int i, j, n, m, k, t;
struct node *root;
while(scanf("%s", a) != EOF)
{
l = 0;
root = (struct node *)malloc(sizeof(struct node));
root =creat();
k = leave(root);
printf("%d\n", k);
}
return 0;
}
本文共计416个文字,预计阅读时间需要2分钟。
数据结构实验之二叉树三:统计叶子节点数 + 时间限制:1000 ms + 内存限制:65536 KiB + 提交统计问题描述:已知二叉树的一个按先序遍历的输入序列,如abc, de, g, f, (其中,表示空节点)。请编写程序统计二叉树中叶子节点的数量。
数据结构实验之二叉树三:统计叶子数
Time Limit:1000 msMemory Limit:65536 KiB
SubmitStatistic
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 <stdlib.h>
#include <string.h>
char a[101];
int l;
struct node//二叉树的定义
{
char data;
struct node *lc;
struct node *rc;
};
struct node *creat()
{
struct node *root;
char c;
c = a[l++];
if(c == ',')
{
return NULL;
}
else
{
root = (struct node *)malloc(sizeof(struct node));
root->data = c;
root->lc = creat();
root->rc = creat();
}
return root;
}
int leave(struct node *root)
{
if(root == NULL)
{
return 0;
}
if(root->lc == NULL && root->rc == NULL)
{
return 1;
}
else
return leave(root->lc) + leave(root->rc);
}
int main()
{
int i, j, n, m, k, t;
struct node *root;
while(scanf("%s", a) != EOF)
{
l = 0;
root = (struct node *)malloc(sizeof(struct node));
root =creat();
k = leave(root);
printf("%d\n", k);
}
return 0;
}

