Problem · Tree

Tree Diameter

Learn this problem
MediumQualcommFULLTIMEPHONE SCREEN

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

Examples

Example 1

edges = [[0,1],[0,2]]return = 2

The longest path is 1 - 0 - 2, which contains 2 edges.

Example 2

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

One longest path is 3 - 2 - 1 - 4 - 5, which contains 4 edges.

Example 3

edges = []return = 0

An empty edge list represents a one-node tree, whose longest path has 0 edges.

More Qualcomm problems

drafts saved locally
public int treeDiameter(int[][] edges) {
    // write your code here
}
edges[[0,1],[0,2]]
expected2
checking account