题目描述

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:

1
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:

1
2
3
4
5
6
2 1
01 1 02



结尾无空行

Sample Output:

1
2
3
4
5
0 1



结尾无空行

参考柳婼的题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// Created by 张旭辉 on 2021/8/11.
//
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int nums[100]; // 每一层叶子节点的个数
vector<int> node[100]; //二维数组存放数
int maxDep = -1;

/**
* 深度优先搜索
* @param index 当前的节点的索引
* @param depth 当前的深度
*/
void dfs(int index,int depth){
//到达当前节点需要做的事情
//这里是判断时候有叶子节点,没有就给当前层数的 nums 加 1
if(node[index].size() == 0){
nums[depth]++;
maxDep = max(depth,maxDep);
return ;
}

//下面这个循环,其实是dfs的模板,也是回溯的模板
for(int i = 0 ; i < node[index].size(); i++){

//TODO 如果是回溯,前置操作
dfs(node[index][i],depth +1);
//TODO 如果是回溯,后置操作

}
}
int main(){
fill(nums,nums+100,inf);
int n,m;
int curNode ,num;
int val;
scanf("%d %d", &n,&m);
//这里看题目的意思,我反正是没有理解透,看了柳神代码才恍然大悟
for(int i = 0; i < m; i++){
scanf("%d %d",&curNode,&num);
for(int j = 0 ; j < num; j++){
scanf("%d",&val);
node[curNode].push_back(val);
}
}

dfs(1,0);
cout<<nums[0];
for(int i =1; i <= maxDep; i++){
cout<<" "<<nums[i];
}
cout<<endl;
return 0;
}

总结

DFS 模板(我精通java,会写一点C++)

1
2
3
4
5
6
void traverse(TreeNode root) {
for (TreeNode child : root.children)
// 前序遍历需要的操作
traverse(child);
// 后序遍历需要的操作
}