#include <bits/stdc++.h>
using namespace std;
const int MAXN = 110;
vector<int> T[MAXN];
int num[MAXN];
int max_depth=1;
void countLeaves(int index,int depth){
if(depth>max_depth) max_depth=depth;
if(T[index].size()==0){//叶结点
num[depth]++;
return;
}
for(int i=0;i<T[index].size();i++){
countLeaves(T[index][i],depth+1);
}
}
int main(){
int n,m,tmp,tmpn,tmpt;
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++){
scanf("%02d %d",&tmp,&tmpn);
while(tmpn--){
scanf("%02d",&tmpt);
T[tmp].push_back(tmpt);
}
}
countLeaves(1,1);
for(int i=1;i<=max_depth;i++){
printf("%s%d",i==1?"":" ",num[i]);
}
return 0;
}
【PAT】1004 Counting Leaves (30 分)
最新推荐文章于 2025-12-18 16:28:22 发布
本文介绍了一段C++代码,用于计算给定树结构中具有最大深度的叶子节点数量。通过递归方法遍历树并更新最大深度,最后输出各深度的叶子节点计数。
421

被折叠的 条评论
为什么被折叠?



