Problem · Tree
Find the Tree Diameter
Learn this problemProblem statement
You are given an undirected tree with n vertices labeled from 0 to n - 1 and an edge list edges.
The diameter is the maximum number of edges on a simple path between any two vertices. Return the tree's diameter. A one-vertex tree has diameter 0.
Function
treeDiameter(n: int, edges: int[][]) → intExamples
Example 1
n = 6edges = [[0,1],[1,2],[1,3],[3,4],[4,5]]return = 4The path 2-1-3-4-5 contains four edges, and no longer simple path exists.
Example 2
n = 1edges = []return = 0A tree with one vertex has no edges, so its diameter is zero.
Constraints
1 <= n <= 200.edges.length = n - 1.- Every edge contains two distinct labels in
[0, n - 1]. - The edges form one connected acyclic undirected graph.