1004 Counting Leaves (30 分)
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0<N<100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.
Sample Input:
2 1
01 1 02
Sample Output:
0 1
来自 <https://pintia.cn/problem-sets/994805342720868352/problems/994805521431773184>
题目思路:
题目意思为求得一颗数的每层叶节点个数,根据题目给出的输入数据。想到可以采用变长动态数组来存储数据。
这里采用数组单链表来存储数据(c++中vector类模板也可实现相同功能)。
数据结构形式为:
#define max 100
typedef struct node{
Int data;
node* next;
}node;
node p[max];
dfs:每向下递归一层,层次等级+1,并且更新根结点,返回递归时,返回原状态,并且在原状态上指针后移到下一位。
代码如下:
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define max 100
typedef struct node{
int data;
struct node *next;
}node;
node p[max];//下标表示根节点
int num[max];//各层次叶节点数
int maxLevel = -1;//最大深度
int main() {
void dfs(int level, int root);
int n, m;//树中节点个数,非叶节点个数
/*初始化数组链表*/
for (int i = 0; i < max; ++i) {
p[i].data = 0;
p[i].next = NULL;
}
scanf("%d %d", &n, &m);
memset(num, 0, max);//初始化各层次节点数
for (int i = 0; i < m; ++i) {
int root, k;
scanf("%d %d", &root, &k);
node *temp = &p[root];
/*构建数组链表*/
for (int j = 0; j < k; ++j) {
node *q = (node*)malloc(sizeof(node));
scanf("%d", &q->data);
q->next = temp->next;
temp->next = q;
temp = temp->next;
}
p[root].data = k;//存储孩子节点个数
temp->next = NULL;
}
dfs(0, 1);
printf("%d", num[0]);
for (int i = 1; i <= maxLevel; ++i) {
printf(" %d", num[i]);
}
return 0;
}
void dfs(int level, int root)
{
node *temp = &p[root];
if (temp->data == 0) {
num[level]++;
if (level > maxLevel) maxLevel = level;
return ;
}
for (int i = 0; i < temp->data && temp->next != NULL; ++i) {
dfs(level+1, temp->next->data);
temp = temp->next;
}
}