Problem
Ask
Submissions

Problem: Tree Diameter

Medium
30 min
Explore how to determine the diameter of an undirected tree by understanding graph structures and applying algorithms to find the longest path between any two nodes. This lesson helps you implement efficient solutions using node-edge representations and deepens your graph problem-solving skills.

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

Problem
Ask
Submissions

Problem: Tree Diameter

Medium
30 min
Explore how to determine the diameter of an undirected tree by understanding graph structures and applying algorithms to find the longest path between any two nodes. This lesson helps you implement efficient solutions using node-edge representations and deepens your graph problem-solving skills.

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