用java写一个计算树直径的代码
时间: 2023-04-09 16:02:51 浏览: 125
javascript写的树
好的,以下是用Java写一个计算树直径的代码:
```
import java.util.*;
public class TreeDiameter {
static int maxDiameter = 0;
static int farthestNode = 0;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 1; i < n; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
visited = new boolean[n + 1];
dfs(graph, 1, 0);
visited = new boolean[n + 1];
dfs(graph, farthestNode, 0);
System.out.println(maxDiameter);
}
static void dfs(List<List<Integer>> graph, int node, int depth) {
visited[node] = true;
if (depth > maxDiameter) {
maxDiameter = depth;
farthestNode = node;
}
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(graph, neighbor, depth + 1);
}
}
}
}
```
希望能够帮到你!
阅读全文