找每层的没有孩子结点的个数
在分层的时候注意如何确定在哪一层。我的做法是用个队列。当每行第一个元素再出队的时候就是一行完了。
这里注意加入下一行的第一个元素的时候要小心处理。不然会出错。
附上AC代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int level[101] = { 0 };
int le = 0;
int main() {
int N, M;
int Head, Num, Temp;
int t, pre;
bool tag = false;
level[0] = 0;//根节点非空 必然第一层没有叶结点
cin >> N >> M;
vector <int> Tree[102];
queue <int> Q;
for (int i = 0; i < M; i++) {
cin >> Head >> Num;
for (int j = 0; j < Num; j++) {
cin >> Temp;
Tree[Head].push_back(Temp);
}
}
//for (int i = 1; i <= N; i++) {
// cout << "==========" << i << "==========" << endl;
// cout << Tree[i].size() << endl;
//}
if (Tree[1].size() == 0) //只有根节点
cout << "1" << endl;
else {//否则层序遍历
Q.push(1);
pre = 1;
while (!Q.empty()) {
t = Q.front();
// cout << "t: " << t << " " << Tree[t][0] << " " << Tree[t].size() << endl;
if (t == pre) {
le++;
tag = true;
}
Q.pop();//出队
if (Tree[t].size() == 0) {
level[le]++;
}
else {
for (int i = 0; i < Tree[t].size(); i++) {
// cout << "i: " << i << " Child: "<< Tree[t][i] <<" Size : " << Tree[t].size() << endl;
if (tag) {
pre = Tree[t][i];
tag = false;
// cout << "pre " << pre << endl;
}
Q.push(Tree[t][i]);
// cout << Q.size() << endl;
}
}
}
for (int i = 1; i <= le; i++)
{
if (i == le)
cout << level[i] << endl;
else
cout << level[i] << " ";
}
}
system("pause");
return 0;
}