Tree Diameter

Try to solve the Tree Diameter problem.

Statement

Given an undirected tree with nn nodes labeled from 00 to n1n - 1, represented by a 2D array edges where edges.length==n1edges.length == n - 1. Each edges[i]=[ai,bi]edges[i] = [a_i, b_i] denotes an undirected edge between nodes aia_i and bib_i. Your task is to return the diameter of the tree.

The diameter of a tree is the number of edges in the longest path between any two nodes.

Constraints:

  • n ==== edges.length +1+ 1

  • edges[i].length = 2

  • 1 <=<= nn <=<=10310^3

  • 0 <=<= ai,bia_i, b_i << nn

  • aia_i bi\neq b_i

Examples

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.