6、 (★、※)root that results in a highest tree

问题:对于一棵特定的树,选择合适的根结点,使得树的高度最大。

思路

  1. 先选择一个结点,从该结点开始遍历整棵树,获取能达到的最深的顶点(记为结点集合A);
  2. 然后从集合A中任意一个结点出发遍历整棵树,获取能达到的最深的顶点(记为结点集合B);
  3. 集合A与集合B的并集即为所求的使树高最大的根结点。

关键代码:

bool vis[maxn];
int maxDepth = -1;
set<int> A, B;


void DFS(int u,int depth) {
    vis[u] = true;
    if (depth > maxDepth) {
        maxDepth = depth;
        A.clear();
        A.insert(u);
    }
    else if (depth == maxDepth) {
        A.insert(u);
    }
    for (int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        if (vis[v] == false) {
            DFS(v,depth+1);
        }
    }
}
原文地址:https://www.cnblogs.com/fuqia/p/9542896.html