Skip to content

Commit 29cd4b1

Browse files
committed
1245. Tree Diameter
1 parent bcd3702 commit 29cd4b1

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

tree-diameter.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Runtime: 52 ms
2+
// Memory Usage: 20.3 MB
3+
class Solution {
4+
public:
5+
int mdepth = 0;
6+
int node = 0;
7+
8+
void dfs(vector<vector<int> > &adj, vector<bool> &vis, int src, int depth) {
9+
vis[src] = true;
10+
for (int a : adj[src]) {
11+
if (!vis[a]) {
12+
dfs(adj, vis, a, depth + 1);
13+
}
14+
}
15+
if (depth > mdepth) {
16+
mdepth = depth;
17+
node = src;
18+
}
19+
}
20+
21+
int treeDiameter(vector<vector<int>>& edges) {
22+
vector<vector<int> > adj(edges.size() + 1, vector<int>());
23+
for (auto a : edges) {
24+
adj[a[0]].push_back(a[1]);
25+
adj[a[1]].push_back(a[0]);
26+
}
27+
vector<bool> vis(edges.size() + 1, 0);
28+
dfs(adj, vis, 0, 0);
29+
vis = vector<bool>(edges.size() + 1, 0);
30+
dfs(adj, vis, node, 0);
31+
return mdepth;
32+
}
33+
};

0 commit comments

Comments
 (0)