forked from Astha369/CPP_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiameter_Of_Tree.cpp
60 lines (48 loc) · 864 Bytes
/
Diameter_Of_Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+10;
vector<int> g[N];
vector<int> depth(N);
void dfs(int v,int par=-1)
{
for(auto child:g[v])
{
if(child==par) continue;
depth[child]=depth[v]+1;
dfs(child,v);
}
}
int main()
{
// Enter the number of nodes in the tree
int n;
cin>>n;
//Enter all the edges in the tree one by one
for(auto i=0;i<n-1;i++)
{
int x,y;
cin>>x>>y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1);
int ans=-1,bro;
for(auto i=1;i<=n;i++)
{
if(depth[i]>ans)
{
ans=depth[i];
bro=i;
}
depth[i]=0;
}
dfs(bro);
for(auto i=1;i<=n;i++)
{
if(depth[i]>ans)
{
ans=depth[i];
}
}
cout<<ans<<endl;
}