Problem · Tree
Tree Diameter
Learn this problemProblem statement
You are given an array edges describing an undirected tree. Each entry edges[i] = [u, v] represents an edge between nodes u and v.
The diameter of a tree is the number of edges in its longest path between any two nodes.
Return the diameter of the tree.
Function
treeDiameter(edges: int[][]) → intExamples
Example 1
edges = [[0,1],[0,2]]return = 2The longest path is 1 - 0 - 2, which contains 2 edges.
Example 2
edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]return = 4One longest path is 3 - 2 - 1 - 4 - 5, which contains 4 edges.
Example 3
edges = []return = 0An empty edge list represents a one-node tree, whose longest path has 0 edges.