关注我 一起刷完pat甲级题库
中文题面:
题目描述
家庭关系可以用家谱树来表示,给定一个家谱树,你的任务是找出其中没有孩子的成员。
输入格式
第一行包含一个整数 N 表示树中结点总数以及一个整数 M 表示非叶子结点数。
接下来 M 行,每行的格式为:
ID K ID[1] ID[2] … ID[K]
ID 是一个两位数字,表示一个非叶子结点编号,K 是一个整数,表示它的子结点数,接下来的 K 个 ID[i] 也是两位数字,表示一个子结点的编号。
为了简单起见,我们将根结点固定设为 01。
所有结点的编号即为 01,02,03,…,31,32,33,…,N。
输出格式
输出从根结点开始,自上到下,树的每一层级分别包含多少个叶子节点。
输出占一行,整数之间用空格隔开。
数据范围
0<N<100
思路
根据输入构建树,再广度优先搜索(bfs)
AC代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt();
List<List<Integer>> tree=new ArrayList();//树
for(int i=0;i<=n;i++)
tree.add(new ArrayList());
for(int i=0;i<m;i++){//构建树
int root=sc.nextInt(),k=sc.nextInt();
for(int j=0;j<k;j++)
tree.get(root).add(sc.nextInt());
}
Deque<Integer> queue=new LinkedList();
queue.add(1);
while(!queue.isEmpty()){
int size=queue.size();
int count=0;//每一层节点的个数
while(size!=0){
int root=queue.removeFirst();
if(tree.get(root).size()==0)
count++;
else{
for(int a:tree.get(root)){
queue.add(a);
}
}
size--;
}
System.out.print(count+" ");
}
}
}