题意
题目提供结点数和非叶子结点的孩子和数目。求每一层的非叶子结点数目。
注意点
- 当只有一个根结点时,该根结点也算叶子结点
题解
BFS广度优先搜索:
#include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 110;
//定义结点
struct node {
int layer;
vector<int> child;
} Node[maxn];
//变量
int n, nonLeaf, leaf[maxn] = {0};//layer[]记录每层有多少个没有孩子的结点
//BFS
int layerNum;//一共有多少层
void BFS(int &root) {
queue<int> q;
q.push(root);
Node[root].layer = 1;
layerNum = 1;//只有根节点,只有一层
while (!q.empty()) {
int now = q.front();
q.pop();
if (Node[now].child.size() == 0) leaf[Node[now].layer]++;
for (int i = 0; i < Node[now].child.size(); i++) {
int child = Node[now].child[i];
q.push(child);
Node[child].layer = Node[now].layer + 1;
if (Node[child].layer > layerNum) {
layerNum = Node[child].layer;
}
}
}
}
int main() {
scanf("%d%d", &n, &nonLeaf);
//读入子结点
for (int i = 0; i < nonLeaf; i++) {
int index, childNum;
scanf("%d%d", &index, &childNum);
for (int j = 0; j < childNum; j++) {
int temp;
scanf("%d", &temp);
Node[index].child.push_back(temp);
}
}
int root = 1;
BFS(root);
for (int i = 1; i <= layerNum; i++) {
printf("%d", leaf[i]);
if (i != layerNum) printf(" ");
else printf("\n");
}
return 0;
}
DFS深度优先搜索:
略