Tutte le sfide
Media 1 risolta 100.0% di accettazione

Tree Diameter

A tree is a connected undirected graph with no cycles.

Cosa imparerai

  • Find the farthest node with a traversal
  • Use two BFS passes to get the diameter
  • Represent a tree with adjacency lists

Problema

Mostra traduzione

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.

Vincoli

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.

Esempi

Esempio 1
Input:
vertices = 5
edges = [
    [1, 2],
    [2, 3],
    [3, 4],
    [2, 5]
]

Output atteso:
expected = 3
Input:
long long vertices = 5;
std::vector<std::vector<long long>> edges = {
    {1, 2},
    {2, 3},
    {3, 4},
    {2, 5}
};

Output atteso:
long long expected = 3;
Input:
long vertices = 5;
long[][] edges = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3},
    new long[] {3, 4},
    new long[] {2, 5}
};

Output atteso:
long expected = 3;

Spiegazione

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

Esempio 2
Input:
vertices = 1
edges = []

Output atteso:
expected = 0
Input:
long long vertices = 1;
std::vector<std::vector<long long>> edges = {};

Output atteso:
long long expected = 0;
Input:
long vertices = 1;
long[][] edges = new long[][] {};

Output atteso:
long expected = 0;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

In a tree, the longest path can be found by two graph searches instead of checking every pair of vertices.

Suggerimento 2

Start from any vertex, find the farthest vertex, then search again from there to measure the longest distance.

Suggerimento 3

Count edges, not vertices, and remember a single-vertex tree has diameter zero.

Complessità attesa

O(vertices) time, O(vertices) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 825 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.