Diameter of an Undirected Tree

Quick Overview

Compute the number of edges in the longest simple path of a large undirected tree in linear time.

Diameter of an Undirected Tree

Company: Salesforce

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

# Diameter of an Undirected Tree Implement `tree_diameter(n: int, edges: list[list[int]]) -> int`. The graph has nodes labeled from `0` through `n - 1`. `edges` describes an undirected connected acyclic graph. Return the diameter: the maximum number of edges on a simple path between any two nodes. ### Input Domain - `1 <= n <= 200,000`. - `len(edges) = n - 1`. - Every edge is `[u, v]` with distinct valid node labels. - The edges form one tree and contain no duplicates. ### Output Rules - Return `0` when `n = 1`. - Measure path length in edges, not nodes. - Return one integer; if several paths attain the diameter, no endpoint tie-break is needed. ### Constraints - Target time is `O(n)`. - Target additional space is `O(n)`. ### Examples #### Example 1 Input: `n = 4, edges = [[0,1],[1,2],[1,3]]` Output: `2` #### Example 2 Input: `n = 1, edges = []` Output: `0` ```hint Use an extreme endpoint Starting from any node, a farthest reachable node can serve as one endpoint of a diameter. ```

Overview: Compute the number of edges in the longest simple path of a large undirected tree in linear time.

|Home/Coding & Algorithms/Salesforce
Salesforce logo
Salesforce
Aug 12, 2026
mediumSoftware EngineerOnsiteCoding & Algorithms
0
0

Diameter of an Undirected Tree

Implement tree_diameter(n: int, edges: list[list[int]]) -> int.

The graph has nodes labeled from 0 through n - 1. edges describes an undirected connected acyclic graph. Return the diameter: the maximum number of edges on a simple path between any two nodes.

Input Domain

  • 1 <= n <= 200,000 .
  • len(edges) = n - 1 .
  • Every edge is [u, v] with distinct valid node labels.
  • The edges form one tree and contain no duplicates.

Output Rules

  • Return 0 when n = 1 .
  • Measure path length in edges, not nodes.
  • Return one integer; if several paths attain the diameter, no endpoint tie-break is needed.

Constraints

  • Target time is O(n) .
  • Target additional space is O(n) .

Examples

Example 1

Input: n = 4, edges = [[0,1],[1,2],[1,3]]

Output: 2

Example 2

Input: n = 1, edges = []

Output: 0

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...