Diameter of an Undirected Tree
SalesforceSoftware Engineer · OnsiteLast updated
Tests your ability to traverse an unrooted, undirected tree to compute its diameter (longest simple path) in linear time and space.
Problem Statement
You are given an undirected, unweighted tree consisting of n nodes labeled from 0 to n - 1. The tree is represented by an array edges of length n - 1, where each edges[i] = [u, v] indicates an undirected edge between node u and node v.
The diameter of a tree is defined as the number of edges on the longest simple path between any two nodes in the tree.
Write a function that returns the diameter of the tree.
Function Signature
def tree_diameter(n: int, edges: list[list[int]]) -> int:
pass
Input & Output Format
- Input:
- An integer
n, the number of nodes. - A 2D list of integers
edges, whereedges[i]contains two integersuandvrepresenting an edge.
- An integer
- Output:
- An integer representing the length (number of edges) of the longest path.
Constraints
1 <= n <= 10^5edges.length == n - 10 <= edges[i][0], edges[i][1] < nedges[i][0] != edges[i][1]- The given edges are guaranteed to form a valid, connected tree.
Examples
Example 1
Input: n = 4, edges = [[0, 1], [1, 2], [2, 3]]
Output: 3
Explanation: The longest path connects node 0 to node 3 (0 - 1 - 2 - 3), which consists of 3 edges.
Example 2
Input: n = 6, edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 5]]
Output: 4
Explanation: One longest path is 3 - 1 - 0 - 2 - 5, which consists of 4 edges.
Edge Cases
n = 1withedges = []: A single node has a diameter of0.- Linear chain graph: The diameter is
n - 1; beware of recursion limit if using recursion in Python. - Star graph: A central node connected to
n - 1leaves has a diameter of2(forn >= 3).
Hints
Hint 1
From any arbitrary start node, the farthest node found via BFS or DFS is guaranteed to be one of the endpoints of a diameter path.
Hint 2
Running a second BFS or DFS from that farthest node will find the distance to the opposite endpoint of the diameter.
Hint 3
Alternatively, you can root the tree arbitrarily and use dynamic programming / post-order traversal to compute the top two maximum depths under each node.
Follow-up questions
- How would you modify your solution to return the actual sequence of node IDs along the longest path instead of just its length?
- Does the two-pass BFS/DFS algorithm still hold if edges have arbitrary non-negative weights? What if negative edge weights are permitted?
- If the tree is skewed into a straight line of 100,000 nodes, how do you prevent recursion stack overflow issues?
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.