Diameter of an Unweighted Tree
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given n vertices labeled 0 through n - 1 joined by n - 1 bidirectional unweighted links edges that form a single tree, compute the diameter of the tree.
In an unweighted tree, every pair of vertices is connected by a unique simple path (a walk with no repeated vertices or links). The tree's diameter equals the largest link count across all simple paths in the tree. When the tree has only a single vertex (n = 1 and edges = []), no links can be traversed, so the diameter is 0.
Implement:
def tree_diameter(n: int, edges: list[list[int]]) -> int:
...
Each entry [u, v] in edges connects vertex u and vertex v in both directions. Return the maximum link count along any simple path.
Examples
Example 1
n = 7
edges = [[0, 2], [2, 1], [2, 3], [3, 4], [4, 5], [3, 6]]
Output:
4
Walk-through: Vertex 2 connects leaves 0 and 1 on one side to vertex 3 on the other, while vertex 3 branches to leaf 6 and the two-edge arm 3 - 4 - 5. The longest simple paths are 0 - 2 - 3 - 4 - 5 and 1 - 2 - 3 - 4 - 5, each spanning 4 edges.
Example 2
n = 5
edges = [[4, 0], [4, 1], [4, 2], [4, 3]]
Output:
2
Walk-through: Vertex 4 acts as a central hub directly connected to leaves 0, 1, 2, and 3. Every path between two distinct leaves crosses 2 edges through vertex 4 (such as 0 - 4 - 2).
Constraints
1 <= n <= 100_000len(edges) == n - 1- Every edge
[u, v]satisfies0 <= u, v < nandu != v edgesforms a single connected, cycle-free undirected graph
Step-by-step walkthrough
Understand the goal and what "diameter" means
We are given
nnodes labeled0throughn - 1connected byn - 1undirected edges[u, v]with no cycles — an undirected tree. Because a tree has no loops, every pair of nodes is connected by one unique simple path (a walk that never repeats a node or edge).A tree's diameter measures the largest edge count across all simple paths in the tree:
- A single node (
n = 1,edges = []) has0edges -> diameter0. - Two connected nodes (
n = 2,edges = [[0, 1]]) have1edge -> diameter1.
Watch out for a classic beginner trap: the longest path in the tree does not have to start at node
0, or even pass through node0! Look at this 8-node tree where node0sits on a short side twig:4 - 3 - 2 - 1 - 5 - 6 - 7 <-- longest path (4 to 7) has 6 edges! | 0 <-- farthest distance from node 0 is only 4!Here, measuring distances only from node
0gives4(from0to4or7), missing the true diameter of6(from4to7). And becausencan be as large as100,000, our solution must run inO(n)linear time without hitting Python's recursion limit on a100,000-node chain.- A single node (
Why the brute-force approach is too slow
How do we measure distances from a single starting node in an unweighted graph? We run breadth-first search (BFS), which explores nodes layer by layer (distance
0, then1, then2, and so on) inO(n)time.A straightforward brute-force solution runs BFS starting from every node
0, 1, ..., n - 1and keeps the largest distance seen anywhere. That is guaranteed to find the diameter, and we can use it to test small random trees, butnruns ofO(n)BFS takeO(n^2)time — roughly10^10operations whenn = 100,000, which will time out.Notice why
O(n^2)is wasteful: if someone simply whispered one endpoint (say node4above) of a longest path to us, a single BFS starting at4would walk all the way to7and hand us the diameter inO(n)time! So the whole problem boils down to: how can we find one true endpoint of a longest path fast?Key insight: any farthest node is already a diameter endpoint
Imagine the tree is built out of string and wooden beads lying on a table:
- Pass 1: Pinch any bead (say bead
0) and lift the tree up so gravity pulls every branch downward. Whichever bead hangs the lowest (end_a) must be one tip of a longest path in the entire tree! - Pass 2: Now grab the tree by
end_aand lift it up again. The entire longest path now hangs straight down fromend_ato the new lowest beadend_b, and its length is the exact diameter!
Why is
end_aguaranteed to be an endpoint of a longest path, even when node0is on a side twig? Picture any true longest pathu --- vin the tree. Because a tree has only one route between paths, the walk starting at0joinsu --- vat some junction nodex(which could be onu --- vitself):0 (start of Pass 1) | u ----- x --------- v (suppose u---v is a longest path) \ \-------- end_a (farthest node from 0)Think about the journey from
0: to reachuorv, we first walk0 -> xand then finish alongx -> uorx -> v. Sinceend_ais at least as far from0asvis, the branch afterxtowardend_amust be at least as long asx -> v(and even ifend_abranched off earlier abovex, its detour is even longer!). That means swapping thex -> vhalf for the route toend_agives a pathu -> x -> ... -> end_athat is at least as long asu --- v— provingend_ais itself an endpoint of a longest path!- Pass 1: Pinch any bead (say bead
Build the adjacency list and iterative BFS helper
To walk from any node to its neighbors in
O(1)per edge, we first convertedgesinto an adjacency listadj, whereadj[u]holds every neighbor connected tou. Because edges have no direction,[u, v]addsvtoadj[u]andutoadj[v].Inside
bfs_farthest(adj, start_node), we pay attention to three practical details: 1. Distance + visited in one list: Initializedist = [-1] * len(adj)anddist[start_node] = 0. A value of-1means "not visited yet," preventing the search from bouncing back and forth across the same undirected edge. 2. Usecollections.deque, notlist.pop(0): A deque (double-ended queue) pops from the front inO(1)constant time, whereaslist.pop(0)shifts every remaining element inO(n)time. 3. Iterative loop, not recursion: A100,000-node straight line has depth99,999, which would crash a recursive DFS withRecursionError(Python's default stack limit is1,000). Awhile queue:loop uses heap memory safely at any depth.from collections import deque def build_adjacency(n: int, edges: list[list[int]]) -> list[list[int]]: """Build undirected adjacency lists for nodes 0 .. n - 1.""" # adj[u]: list of neighbor node IDs directly connected to node u. adj: list[list[int]] = [[] for _ in range(n)] for u, v in edges: # Add both directions because edges can be traversed either way. adj[u].append(v) adj[v].append(u) return adj def bfs_farthest(adj: list[list[int]], start_node: int) -> tuple[int, int]: """Return (farthest_node, max_edge_distance) starting from start_node.""" # dist[v]: edge count from start_node to v, or -1 if v has not been visited yet. dist = [-1] * len(adj) dist[start_node] = 0 # queue: FIFO deque of visited nodes whose neighbors still need to be explored. # Iterative BFS with deque avoids Python's 1000-call recursion limit on long chains. queue = deque([start_node]) farthest_node = start_node while queue: curr = queue.popleft() if dist[curr] > dist[farthest_node]: farthest_node = curr for neighbor in adj[curr]: # Checking dist[neighbor] == -1 prevents walking backward to our parent. if dist[neighbor] == -1: dist[neighbor] = dist[curr] + 1 queue.append(neighbor) return farthest_node, dist[farthest_node]Combine the two BFS passes
With
build_adjacencyandbfs_farthestready,tree_diameteris just three steps: handle the0-edge base casen <= 1, run Pass 1 from node0to locate endpointend_a, and run Pass 2 fromend_ato measure the diameter.def tree_diameter(n: int, edges: list[list[int]]) -> int: # A tree with 0 or 1 node has no edges, so its longest path has 0 edges. if n <= 1: return 0 adj = build_adjacency(n, edges) # Pass 1: Any farthest node from node 0 is guaranteed to be one endpoint # of a longest path in the tree. end_a, _ = bfs_farthest(adj, 0) # Pass 2: Measuring the farthest distance from end_a sweeps across the # entire longest path to its opposite endpoint. _, diameter = bfs_farthest(adj, end_a) return diameterTrace Example 1 step by step
Let's trace
n = 7,edges = [[0, 2], [2, 1], [2, 3], [3, 4], [4, 5], [3, 6]]:Tree shape: 1 --- 2 --- 3 --- 4 --- 5 | | 0 6 Pass 1 (start_node = 0): Layer 0: visit 0 -> dist[0] = 0, farthest = 0 Layer 1: visit 2 (from 0) -> dist[2] = 1, farthest = 2 Layer 2: visit 1, 3 (from 2) -> dist[1] = 2, dist[3] = 2, farthest = 1 Layer 3: visit 4, 6 (from 3) -> dist[4] = 3, dist[6] = 3, farthest = 4 Layer 4: visit 5 (from 4) -> dist[5] = 4, farthest = 5 Result of Pass 1: end_a = 5 Pass 2 (start_node = 5): Layer 0: visit 5 -> dist[5] = 0 Layer 1: visit 4 -> dist[4] = 1 Layer 2: visit 3 -> dist[3] = 2 Layer 3: visit 2, 6 -> dist[2] = 3, dist[6] = 3 Layer 4: visit 0, 1 -> dist[0] = 4, dist[1] = 4 Result of Pass 2: diameter = 4 (path 5 - 4 - 3 - 2 - 0 or 5 - 4 - 3 - 2 - 1)Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def build_adjacency(n: int, edges: list[list[int]]) -> list[list[int]]: """Build undirected adjacency lists for nodes 0 .. n - 1.""" # adj[u]: list of neighbor node IDs directly connected to node u. adj: list[list[int]] = [[] for _ in range(n)] for u, v in edges: # Add both directions because edges can be traversed either way. adj[u].append(v) adj[v].append(u) return adj def bfs_farthest(adj: list[list[int]], start_node: int) -> tuple[int, int]: """Return (farthest_node, max_edge_distance) starting from start_node.""" # dist[v]: edge count from start_node to v, or -1 if v has not been visited yet. dist = [-1] * len(adj) dist[start_node] = 0 # queue: FIFO deque of visited nodes whose neighbors still need to be explored. # Iterative BFS with deque avoids Python's 1000-call recursion limit on long chains. queue = deque([start_node]) farthest_node = start_node while queue: curr = queue.popleft() if dist[curr] > dist[farthest_node]: farthest_node = curr for neighbor in adj[curr]: # Checking dist[neighbor] == -1 prevents walking backward to our parent. if dist[neighbor] == -1: dist[neighbor] = dist[curr] + 1 queue.append(neighbor) return farthest_node, dist[farthest_node] def tree_diameter(n: int, edges: list[list[int]]) -> int: # A tree with 0 or 1 node has no edges, so its longest path has 0 edges. if n <= 1: return 0 adj = build_adjacency(n, edges) # Pass 1: Any farthest node from node 0 is guaranteed to be one endpoint # of a longest path in the tree. end_a, _ = bfs_farthest(adj, 0) # Pass 2: Measuring the farthest distance from end_a sweeps across the # entire longest path to its opposite endpoint. _, diameter = bfs_farthest(adj, end_a) return diameter✅ Submit now — all tests should pass.
Intuition & how it works
Picture an undirected tree (a connected network of n nodes and n - 1 two-way links with no loops) as a floppy cluster of beads tied together with pieces of string. If you pinch any random bead — say bead 0 — and hold it up in the air, gravity pulls the strings downward, and whichever bead dangles the lowest (end_a) is guaranteed to be one tip of the longest string in the whole cluster. If you then pinch end_a and lift the cluster a second time, that entire longest path stretches straight down from end_a to the opposite tip, giving us the diameter (the maximum number of edges along any simple path, meaning a walk that never repeats a node).
The naive approach runs a breadth-first search (BFS) — a traversal that visits nodes in expanding rings of distance 0, 1, 2, ... — starting separately from every node 0 .. n - 1. That checks all pairs accurately, but n searches of O(n) work cost O(n^2) time, which means roughly 10^10 steps when n = 100,000. Equally tempting is running just one BFS from node 0, which fails whenever node 0 sits near the middle of the tree (a 3-node chain 1 - 0 - 2 has distance 1 from 0, even though 1 to 2 is 2 edges!). Doing two BFS passes gets the exact diameter in O(n) linear time.
Let's trace Example 2, a 5-node star centered at node 4: edges = [[4, 0], [4, 1], [4, 2], [4, 3]].
1. Pass 1 from node 0: Distance is 0 at node 0, 1 at the hub 4, and 2 at leaves 1, 2, and 3. A farthest node found is end_a = 1 (at distance 2).
2. Pass 2 from node 1: Distance is 0 at 1, 1 at 4, and 2 at 0, 2, and 3. The maximum distance reached in Pass 2 is 2, which is the diameter (1 - 4 - 2).
Complexity
- Time —
O(n): Building the adjacency list (an array whereadj[u]lists all neighbors directly attached tou) loops once overn - 1edges. Each of the two BFS passes enqueues and pops each of thennodes once and inspects each undirected edge twice (once from each end,2 * (n - 1)neighbor checks per pass), so every step is directly proportional ton. - Space —
O(n): The adjacency list stores2 * (n - 1)integers acrossnlists,distholdsnintegers, and the deque (a double-ended queue supportingO(1)appends at the back andO(1)pops from the front) holds at mostnnode IDs at once.
Edge cases
- Single node (
n = 1,edges = []): There are zero edges, so the longest path has0edges (not1— we count edges, not nodes!). - Single edge (
n = 2,edges = [[1, 0]]): Pass 1 goes0 -> 1and Pass 2 goes1 -> 0, returning1. - Star graph (all nodes attached to one hub): As soon as
n >= 3, every longest path goesleaf -> hub -> another leaf, returning2regardless of whethernis3or100,000and regardless of which node ID is the hub. - Node
0on a short side branch: Pass 1 still climbs out of the side branch onto one true endpoint of the main trunk, and Pass 2 measures the full trunk length. - Long
100,000-node chain: Diameter is99,999. Becausebfs_farthestuses an iterativewhile queue:loop instead of recursion, it never triggers Python'sRecursionErrorstack limit.
Common mistakes
- Returning the max distance from Pass 1 alone: Pass 1 only measures how far nodes are from node
0, which undercounts whenever the longest path passes through0(like1 - 0 - 2) or bypasses0's side branch completely. - Counting nodes instead of edges: A path visiting
5nodes (1 - 2 - 3 - 4 - 5) crosses4edges; initializingdist[start_node] = 1instead of0makes every answer off by1. - Using recursion for DFS on large trees in Python: Python limits call-stack depth to
1,000by default, so a recursive depth-first search crashes withRecursionErroron a chain of100,000nodes. - Adding edges in only one direction (
adj[u].append(v)withoutadj[v].append(u)): Input edges like[3, 0]have no fixed orientation; omitting the reverse direction traps BFS whenever an edge is listed "pointing toward" the start node. - Using
queue.pop(0)on a plain Pythonlist: Popping index0from alistshifts every remaining item left inO(n)time, quietly degrading a star-like BFS intoO(n^2). Always usecollections.deque.popleft().
Alternative approaches
- Single-pass bottom-up tree DP (subtree heights): Root the tree arbitrarily at node
0. Every simple path in a rooted tree has a single highest node (its peak), where the path climbs up one child's subtree (all descendants below that child) and goes down another child's subtree. If we visit nodes in reverse BFS order (bottom-up from leaves to root, staying completely iterative) and computeheight[u]= longest downward chain starting atu, then at each nodeuthe longest path peaking atucombines its two largest values ofheight[child] + 1. This also runs inO(n)time andO(n)space, and unlike the two-BFS trick it still works even if edges can have negative weights!
Follow-up questions
- How would you modify the traversal to return the sequence of nodes along a longest path instead of just its edge count? During Pass 2 (starting from
end_a), keep aparent = [-1] * nlist and setparent[neighbor] = currwheneverdist[neighbor] == -1. Once Pass 2 finishes atend_b, followcurr = parent[curr]backward fromend_buntil-1and reverse the collected list to get[end_a, ..., end_b]inO(n)time and space. - Does the two-pass approach still hold when edges carry positive weights, and what changes if weights can be negative? Yes for positive weights! Because a tree has only one simple path between any two nodes, you do not even need Dijkstra's algorithm (a priority-queue shortest-path search for general graphs) — a plain iterative BFS or stack-based DFS accumulating
dist[neighbor] = dist[curr] + weightcomputes exact distances inO(n)time, and the two-pass proof still holds whenever all edge weights are>= 0. If edges can have negative weights, however, the farthest-node lemma breaks and you should use the bottom-up two-largest-heights DP instead. - How can you locate the center node(s) of the tree that minimize its rooted height? Reconstruct any diameter path
pathofDedges (D + 1nodes) using aparentarray from Pass 2. IfDis even, the single middle nodepath[D // 2]is the unique center (giving minimum possible heightD // 2); ifDis odd, the two middle nodespath[D // 2]andpath[D // 2 + 1]tie as centers (giving minimum possible height(D + 1) // 2).
Follow-up questions
- How would you modify the traversal to return the sequence of nodes along a longest path instead of just its edge count?
- Does the two-pass approach still hold when edges carry positive weights, and what changes if weights can be negative?
- How can you locate the center node(s) of the tree that minimize its rooted height?
Similar questions
- Earliest Faulty Build in Version History
- A* Grid Maze Pathfinding
- C++ Language Semantics and GPU Kernel Trade-offs
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses