题目大意:从01开始的一颗树结构,求解每个层次上叶节点的数目。
解题思路:本题采用 vector 来存储树结构,一个DFS计算树的深度 和 对相应层次非叶节点的数目。
题目链接:https://www.patest.cn/contests/pat-a-practise/1004
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;
const int MAXSIZE = 105;
vector<int> VV[MAXSIZE];
int level[MAXSIZE];
int Depth = -1;
void DFS(int v,int depth)
{
Depth = (Depth>depth)?Depth:depth;
if(VV[v].size() == 0)
{
++level[depth];
return;
}
for(int i=0;i<VV[v].size();++i)
{
DFS(VV[v][i],depth+1);
}
}
int main(int argc, char** argv) {
int n,m,x,num;
fill(level,level+MAXSIZE,0);
cin >> n >> m;
for(int i=0;i<m;++i)
{
cin >> x >> num;
for(int j=0;j<num;++j)
{
int temp;
cin >> temp;
VV[x].push_back(temp);
}
}
DFS(1,1);
for(int i=1;i<Depth;++i)
{
cout<<level[i]<<" ";
}
cout<<level[Depth]<<endl;
return 0;
}