Compute the Diameter of an Undirected Tree
QualcommSoftware Engineer · Technical ScreenLast updated
Compute the diameter of a large undirected tree, measured by the number of edges on its longest simple path. The exercise tests adjacency construction, linear-time tree traversal, endpoint reasoning, recursion-depth awareness, and edge cases such as a single-node tree.
Compute the Diameter of an Undirected Tree
You are given an undirected tree with nodes numbered from 0 through n - 1. The diameter is the number of edges on the longest simple path between any two nodes.
Return the tree's diameter.
Function Signature
def tree_diameter(n: int, edges: list[list[int]]) -> int:
...
Input and Output
- Each element of
edgesis[u, v]and represents one undirected edge. - Return the maximum number of edges on any simple path.
Constraints
1 <= n <= 100_000len(edges) == n - 10 <= u, v < nandu != v- The input graph is connected and contains no cycle.
Examples
Input: n = 5, edges = [[0, 1], [1, 2], [1, 3], [3, 4]]
Output: 3
Input: n = 1, edges = []
Output: 0
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.