树的遍历问题,本题是普通的树,不是二叉树。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
bool st[N]; //判断一个节点是否是子节点
vector<int> g[N]; //储存每个父节点的子节点
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i ++ )
{
int father, son;
cin >> father >> son;
st[son] = true;
g[father].push_back(son);
}
for (int i = 1; i <= 1000; i ++ ) //找根节点
if (g[i].size() && !st[i]) //该节点存在且没有父节点,即是根节点
{
cout << i << endl;
break;
}
int p = 1;
for (int i = 2; i <= 1000; i ++ ) //遍历找子节点最多的节点
if (g[i].size() > g[p].size())
p = i;
cout << p << endl;
sort(g[p].begin(), g[p].end()); //将儿子从小到大排序输出
for (auto x : g[p]) cout << x << ' ';
cout << endl;
return 0;
}