https://www.patest.cn/contests/pat-a-practise/1004
这个题做的不好一开始用 链接法构造树,但是发现如果有的节点的孩子信息先给出,但是他的父节点的孩子信息还没给出(就是这个点还没建出来)。是会出问题的。
开始就就没想到!!!啊!
后来参考了:
http://www.liuchuo.net/archives/2229
#include <cstdio>
#include <queue>
using namespace std;
vector<int> levelOrder(vector<int> tree[], int root) {
vector<int> res;
queue<int> q;
int count = 0;
int lastNode = root, newlastNode=root;
q.push(root);
while (!q.empty()) {
int tnode = q.front();
q.pop();
int nlen = tree[tnode].size();
if (nlen == 0) count++;
for (int i = 0 ; i < nlen; i++)
{
q.push(tree[tnode][i]);
newlastNode = tree[tnode][i];
}
if (tnode == lastNode) {
res.push_back(count);
count = 0;
lastNode = newlastNode;
}
}
return res;
}
int main()
{
//freopen("in.txt", "r", stdin);
int n, m, k, a, b;
scanf("%d %d", &n, &m);
vector<int> tree[100];
for (int i = 0; i < m; i++)
{
scanf("%d %d", &a, &k);
for (int j = 0; j < k; j++)
{
scanf("%d", &b);
tree[a].push_back(b);
}
}
vector<int> res = levelOrder(tree, 1);
int vlen = res.size();
for (int i = 0; i < vlen; i++)
{
if (i != 0) printf(" ");
printf("%d",res[i]);
}
printf("\n");
return 0;
}