【题目来源】
https://www.acwing.com/problem/content/1256/
【题目描述】
 给定一棵树,输出树的根root,孩子最多的结点max以及他的孩子。
【输入格式】
 第一行:n,m,表示树的节点数和边数。
 以下m行:每行两个结点x和y,表示y是x的孩子。
【输出格式】
 第一行:树根:root;
 第二行:孩子最多的结点max;
 第三行:max的孩子(按编号由小到大输出)。
【数据范围】
 1≤n≤100,
 m=n−1,
 1≤x,y≤1000,
 数据保证孩子最多的结点唯一。
【输入样例1】
 8 7
 4 1
 4 2
 1 3
 1 5
 2 6
 2 7
 2 8
【输出样例1】
 4
 2 
 6 7 8
【输入样例2】
 10 9
 661 43
 43 270
 43 155
 155 691
 661 201
 661 768
 661 889
 43 302
 201 98
【输出样例2】
 661
 661
 43 201 768 889
【算法分析】
 本题是树的遍历问题,不是二叉树。
【算法代码】
#include <bits/stdc++.h>
using namespace std;const int N=1010;
bool st[N];
vector<int> g[N];
int fa,son;
int n,m;int main() {cin>>n>>m;for(int i=0; i<m; i++) {cin>>fa>>son;st[son]=true; //has fatherg[fa].push_back(son);}for(int i=1; i<=1000; i++) { //find rootif(g[i].size()) { //if node i has sonif(!st[i]) { //and node i hasn't fathercout<<i<<endl;break;}}}int p=1;for(int i=2; i<=1000; i++) //Find the node with the most sonsif(g[i].size()>g[p].size()) p=i;cout<<p<<endl;sort(g[p].begin(),g[p].end()); //Sort the son from small to bigfor(auto x:g[p]) cout<<x<<" ";cout<<endl;return 0;
}/*
in:
8 7
4 1
4 2
1 3
1 5
2 6
2 7
2 8out:
4
2
6 7 8
*/
【参考文献】
https://www.acwing.com/solution/content/66005/
https://www.acwing.com/solution/content/36119/