[InterviewBit] Largest Distance between nodes of a Tree

Largest Distance between nodes of a Tree

  • Time :
  • Space :
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
int dfs(vector<vector<int>>& adj, int u, int par, int& res) {
priority_queue<int, vector<int>, greater<int>> q;
q.push(0);
q.push(0);
for(auto& v : adj[u]) {
if(v == par) continue;
q.push(dfs(adj,v,u,res));
if(q.size() > 2) q.pop();
}
int less = q.top(); q.pop();
res = max(res, less + q.top());
return q.top() + 1;
}
int Solution::solve(vector<int> &A) {
vector<vector<int>> adj(A.size());
int root = 0;
for(int i = 0; i < A.size(); i++) {
if(A[i] == -1) root = i;
else {
adj[A[i]].push_back(i);
adj[i].push_back(A[i]);
}
}
int res = 0;
dfs(adj, root, -1, res);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/18/PS/interviewbit/largest-distance-between-nodes-of-a-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.