Diameter of a tree

Revision en1, by electro177, 2021-06-29 13:44:02

const int mxN = 2e5; int n, d[mxN], ans; vector<int> adj[mxN]; void dfs(int u = 0, int p = -1) { for (int v : adj[u]) { if (v == p) continue; dfs(v, u); ans = max(d[u] + d[v] + 1, ans); d[u] = max(d[u], d[v] + 1); } }

ans gives the diameter of the tree .It is not that trivial to understand for me.can someone explain please explain how the code works

Tags tree, #diameter, #help me

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English electro177 2021-06-29 13:44:02 427 Initial revision (published)