백준에 트리의 지름이 2가지가 있는 데 어려운 난이도의 풀이로 쉬운 것도 풀 수 있다.
import java.io.*;
import java.util.*;
class Node {
int to, weight;
public Node(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
public class Main {
static ArrayList<Node>[] tree;
static boolean[] visited;
static int maxDistance;
static int maxNode;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
tree = new ArrayList[N + 1];
for (int i = 0; i <= N; i++) {
tree[i] = new ArrayList<>();
}
for (int i = 0; i < N - 1; i++) {
st = new StringTokenizer(br.readLine());
int parent = Integer.parseInt(st.nextToken());
int child = Integer.parseInt(st.nextToken());
int weight = Integer.parseInt(st.nextToken());
tree[parent].add(new Node(child, weight));
tree[child].add(new Node(parent, weight));
}
visited = new boolean[N + 1];
maxDistance = 0;
dfs(1, 0);
visited = new boolean[N + 1];
dfs(maxNode, 0);
System.out.println(maxDistance);
}
public static void dfs(int currentNode, int distance) {
visited[currentNode] = true;
if (distance > maxDistance) {
maxDistance = distance;
maxNode = currentNode;
}
for (Node node : tree[currentNode]) {
if (!visited[node.to]) {
dfs(node.to, distance + node.weight);
}
}
}
}