Problem · Tree

Find the Tree Diameter

Learn this problem
MediumAdyen logoAdyenFULLTIMEONSITE INTERVIEW

Problem 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[][]) → int

Examples

Example 1

n = 6edges = [[0,1],[1,2],[1,3],[3,4],[4,5]]return = 4

The path 2-1-3-4-5 contains four edges, and no longer simple path exists.

Example 2

n = 1edges = []return = 0

A 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.

More Adyen problems

drafts saved locally
public int treeDiameter(int n, int[][] edges) {
    // Return the maximum number of edges on a simple path.
}
n6
edges[[0,1],[1,2],[1,3],[3,4],[4,5]]
expected4
checking account