문제
A tree is a connected undirected graph with no cycles. Its diameter is the largest number of edges on a path between any two vertices. Return that length; you do not need to return the path. No root is specified.
Implement tree_diameter(vertices, edges).
Input
vertices: The number of vertices.
edges: Undirected connections [u, v].
Output
Return the diameter measured in edges, not vertices.
제약 조건
1 ≤ vertices ≤ 200,000. Exactly vertices − 1 edges, with distinct endpoints in 1…vertices. Inputs always form a tree. A one-vertex tree has diameter 0.
예시
입력:
vertices = 5
edges = [
[1, 2],
[2, 3],
[3, 4],
[2, 5]
]
예상 출력:
expected = 3
입력:
long long vertices = 5;
std::vector<std::vector<long long>> edges = {
{1, 2},
{2, 3},
{3, 4},
{2, 5}
};
예상 출력:
long long expected = 3;
입력:
long vertices = 5;
long[][] edges = new long[][] {
new long[] {1, 2},
new long[] {2, 3},
new long[] {3, 4},
new long[] {2, 5}
};
예상 출력:
long expected = 3;
설명
The path 5–2–3–4 contains three edges. No path in this tree is longer.
입력:
vertices = 1
edges = []
예상 출력:
expected = 0
입력:
long long vertices = 1;
std::vector<std::vector<long long>> edges = {};
예상 출력:
long long expected = 0;
입력:
long vertices = 1;
long[][] edges = new long[][] {};
예상 출력:
long expected = 0;
설명
A single vertex has no edges, so the longest path length is 0.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
In a tree, the longest path can be found by two graph searches instead of checking every pair of vertices.
힌트 2
Start from any vertex, find the farthest vertex, then search again from there to measure the longest distance.
힌트 3
Count edges, not vertices, and remember a single-vertex tree has diameter zero.
예상 복잡도
O(vertices) time, O(vertices) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.