forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1245.Tree-Diameter.cpp
More file actions
57 lines (50 loc) · 1.26 KB
/
Copy path1245.Tree-Diameter.cpp
File metadata and controls
57 lines (50 loc) · 1.26 KB
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
class Solution {
vector<vector<int>>adj;
int V;
public:
int treeDiameter(vector<vector<int>>& edges)
{
V = edges.size()+1;
adj.resize(V);
for (auto edge:edges)
{
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
auto t1 = bfs(0);
auto t2 = bfs(t1.first);
return t2.second;
}
pair<int, int> bfs(int u)
{
vector<int>dis(V, -1);
queue<int> q;
q.push(u);
dis[u] = 0;
while (!q.empty())
{
int t = q.front();
q.pop();
for (auto it = adj[t].begin(); it != adj[t].end(); it++)
{
int v = *it;
if (dis[v] == -1)
{
q.push(v);
dis[v] = dis[t] + 1;
}
}
}
int maxDis = 0;
int nodeIdx;
for (int i = 0; i < V; i++)
{
if (dis[i] > maxDis)
{
maxDis = dis[i];
nodeIdx = i;
}
}
return make_pair(nodeIdx, maxDis);
}
};