[LeetCode] Tree Diameter

1245. Tree Diameter

The diameter of a tree is the number of edges in the longest path in that tree.

There is an undirected tree of n nodes labeled from 0 to n - 1. You are given a 2D array edges where edges.length == n - 1 and edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the tree.

Return the diameter of the tree.

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
class Solution {
vector<int> adj[10101];
int res = 0;
int dfs(int u, int par) {
int dis = 0;
priority_queue<int, vector<int>, greater<int>> pq;
for(auto& v : adj[u]) {
if(v == par) continue;
pq.push(dfs(v,u) + 1);
if(pq.size() > 2) pq.pop();
}
if(pq.size() == 2) {
auto tp = pq.top(); pq.pop();
res = max(res, tp + pq.top());
dis = pq.top();
} else if(pq.size()) {
res = max(res, pq.top());
dis = pq.top();
}
return dis;
}
public:
int treeDiameter(vector<vector<int>>& edges) {
for(auto& e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(0, -1);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/04/PS/LeetCode/tree-diameter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.