Funcia
Lv.3bfsdfstree

Tree Diameter

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

n villages are connected by n - 1 two-way roads forming a tree; roads[i] = [a, b, len]. Return the largest distance between any two villages (0 for a single village).

Examples

nroadsresult
5[[0, 1, 3], [1, 2, 4], [1, 3, 2], [3, 4, 6]]12
2[[0, 1, 7]]7
1[]0

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(n: int, roads: int[][]) → long

Constraints

  • 1≤1 \le n ≤200,000\le 200{,}000, roads.length =n−1= n - 1, 1≤len≤1061 \le len \le 10^6; the roads form a tree. The answer can exceed 32 bits.

Expected complexity

Time
O(N)
Space
O(N)

Examples

nroadsExpected
5[[0,1,3],[1,2,4],[1,3,2],[3,4,6]]12
2[[0,1,7]]7
1[]0

Hint

Hint

Search from any village to find the farthest u, then search from u; the largest distance found is the diameter. Use an iterative traversal (deep trees). Searching from every village is O(N2)O(N^2).

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)294 msestimated
C++ (GCC, gnu++23)294 msderived
Python 3.131108 msderived
Java 251632 msderived
Kotlin 2.4 (JVM)1588 msestimated
C# 14 (.NET 10)1588 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness407verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.