Skip to content

Instantly share code, notes, and snippets.

@Chillee
Last active April 4, 2019 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chillee/fe6611ab24303e92cc9664ddde40a337 to your computer and use it in GitHub Desktop.
Save Chillee/fe6611ab24303e92cc9664ddde40a337 to your computer and use it in GitHub Desktop.
Tree Diameter: O(N)
int dfs(int cur, int prv = -1, int d = 0) {
dist[cur] = d;
int mx = cur;
for (auto i : adj[cur]) {
if (i == prv)
continue;
int res = dfs(i, cur, d + 1);
if (dist[res] > dist[mx])
mx = res;
}
return mx;
}
cout<<dist[dfs(dfs(0))]<<endl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment