Given an undirected tree, return its diameter: the number of edges in a longest path in that tree.
The tree is given as an array of edges
where edges[i] = [u, v]
is a bidirectional edge between nodes u
and v
. Each node has labels in the set {0, 1, ..., edges.length}
.
Example 1:
Input: edges = [[0,1],[0,2]] Output: 2 Explanation: A longest path of the tree is the path 1 - 0 - 2.
Example 2:
Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]] Output: 4 Explanation: A longest path of the tree is the path 3 - 2 - 1 - 4 - 5.
Constraints:
0 <= edges.length < 10^4
edges[i][0] != edges[i][1]
0 <= edges[i][j] <= edges.length
- The given edges form an undirected tree.
思路:这题跟 Diameter of Binary Tree 很类似,不同的是,从两个边变成了多个边,那么通过一个node的最大的path,就是通过这个node的最大的len和第二大的len的和,dfs返回的还是通过这个node的最大的length;注意,防止死循环,用parent来表示上一个parent,如果上一个parent == neighbor跳过;
class Solution {
private int maxlen = 0;
public int treeDiameter(int[][] edges) {
if(edges == null || edges.length == 0 || edges[0].length == 0) {
return 0;
}
HashMap<Integer, List<Integer>> graph = new HashMap<>();
int n = edges.length;
for(int i = 0; i < edges.length; i++) {
int u = edges[i][0];
int v = edges[i][1];
graph.putIfAbsent(u, new ArrayList<Integer>());
graph.putIfAbsent(v, new ArrayList<Integer>());
graph.get(u).add(v);
graph.get(v).add(u);
}
dfs(graph, 0, -1);
return maxlen;
}
private int dfs(HashMap<Integer, List<Integer>> graph,
int node, int parent) {
int max1 = 0;
int max2 = 0;
for(Integer neighbor: graph.get(node)) {
if(neighbor == parent) {
continue;
}
int depth = dfs(graph, neighbor, node) + 1;
if(depth > max1) {
max2 = max1;
max1 = depth;
} else if(depth > max2) {
max2 = depth;
}
}
maxlen = Math.max(maxlen, max1 + max2);
return max1;
}
}