Tree Diameter
Last updated
Was this helpful?
Last updated
Was this helpful?
/*
本算法答案由上岸科技提供。
上岸科技是一个专致力于高效培养北美留学生拥有实际面试能力的团体。
我们采用小班化线上,线下教学让学生更快,更好的学习到想要的知识。
团队主要由一群怀揣情怀于美国高校毕业的一线IT公司工程师构成。
我们坚信对于求职者算法并不是全部,合理的技巧加上适当的算法培训能够大大的提升求职成功概率也能大大减少刷题的痛苦。
正如我们的信仰:我们教的是如何上岸而不仅是算法。
更多信息请关注官网:https://www.shanganonline.com/
*/
class Solution {
private Map<Integer, List<Integer>> graph;
private int maxDiameter;
public int treeDiameter(int[][] edges) {
if(edges.length == 0) {
return 0;
}
maxDiameter = 0;
graph = new HashMap<>();
for(int[] edge : edges) {
graph.putIfAbsent(edge[0], new ArrayList<Integer>());
graph.putIfAbsent(edge[1], new ArrayList<Integer>());
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
boolean[] visited = new boolean[graph.size()];
diameter(0, visited);
return maxDiameter - 1;
}
private int diameter(int curr, boolean[] visited) {
if(visited[curr]) {
return 0;
}
visited[curr] = true;
int max1 = 0;
int max2 = 0;
for(int neighbor : graph.get(curr)) {
int m = diameter(neighbor, visited);
if(m > max1) {
max2 = max1;
max1 = m;
} else if(m > max2) {
max2 = m;
}
}
maxDiameter = Math.max(maxDiameter, 1 + max1 + max2);
return max1 + 1;
}
}