Moyen 0 résolus 0 % de réussite

Tree Diameter

A tree is a connected undirected graph with no cycles.

Problème

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.

Contraintes

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.

Exemples

Exemple 1
Entrée :
edges = [
    [1, 2],
    [2, 3],
    [3, 4],
    [2, 5]
]
vertices = 5

Sortie attendue :
expected = 3
Entrée :
std::vector<std::vector<long long>> edges = {
    {1, 2},
    {2, 3},
    {3, 4},
    {2, 5}
};
long long vertices = 5;

Sortie attendue :
long long expected = 3;
Entrée :
long[][] edges = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3},
    new long[] {3, 4},
    new long[] {2, 5}
};
long vertices = 5;

Sortie attendue :
long expected = 3;

Explication

The path 5–2–3–4 contains three edges. No path in this tree is longer.

Exemple 2
Entrée :
edges = []
vertices = 1

Sortie attendue :
expected = 0
Entrée :
std::vector<std::vector<long long>> edges = {};
long long vertices = 1;

Sortie attendue :
long long expected = 0;
Entrée :
long[][] edges = new long[][] {};
long vertices = 1;

Sortie attendue :
long expected = 0;

Explication

A single vertex has no edges, so the longest path length is 0.

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.