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

思路

  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);
        }
    }
}

 

 

相关文章:

  • 2021-04-14
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
  • 2021-10-10
猜你喜欢
  • 2021-10-08
  • 2021-10-01
  • 2022-12-23
  • 2021-07-12
  • 2021-06-21
  • 2022-12-23
  • 2021-05-01
相关资源
相似解决方案