Medium 0 solved 0% acceptance

Tree Diameter

A tree is a connected undirected graph with no cycles.

What you'll learn

  • Find the farthest node with a traversal
  • Use two BFS passes to get the diameter
  • Represent a tree with adjacency lists

Problem

A tree is a connected undirected graph with no cycles. Its diameter is the largest number of edges on a path between any two vertices. Return that length; you do not need to return the path. No root is specified.

Implement tree_diameter(vertices, edges).

Input

vertices: The number of vertices.

edges: Undirected connections [u, v].

Output

Return the diameter measured in edges, not vertices.

Constraints

1 ≤ vertices ≤ 200,000. Exactly vertices − 1 edges, with distinct endpoints in 1…vertices. Inputs always form a tree. A one-vertex tree has diameter 0.

Examples

Example 1
Input:
edges = [
    [1, 2],
    [2, 3],
    [3, 4],
    [2, 5]
]
vertices = 5

Expected output:
expected = 3
Input:
std::vector<std::vector<long long>> edges = {
    {1, 2},
    {2, 3},
    {3, 4},
    {2, 5}
};
long long vertices = 5;

Expected output:
long long expected = 3;
Input:
long[][] edges = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3},
    new long[] {3, 4},
    new long[] {2, 5}
};
long vertices = 5;

Expected output:
long expected = 3;

Explanation

The path 5–2–3–4 contains three edges. No path in this tree is longer.

Example 2
Input:
edges = []
vertices = 1

Expected output:
expected = 0
Input:
std::vector<std::vector<long long>> edges = {};
long long vertices = 1;

Expected output:
long long expected = 0;
Input:
long[][] edges = new long[][] {};
long vertices = 1;

Expected output:
long expected = 0;

Explanation

A single vertex has no edges, so the longest path length is 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

In a tree, the longest path can be found by two graph searches instead of checking every pair of vertices.

Hint 2

Start from any vertex, find the farthest vertex, then search again from there to measure the longest distance.

Hint 3

Count edges, not vertices, and remember a single-vertex tree has diameter zero.

Expected complexity

O(vertices) time, O(vertices) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.