Imagine you're a city planner tasked with placing a central communication tower in a connected network of cities. The cities are connected by roads forming a tree structure - meaning every city can reach every other city through exactly one path, with no circular routes.

Given n cities labeled from 0 to n-1 and an array of n-1 roads where edges[i] = [a, b] represents a direct road between cities a and b, you need to find the optimal locations for your communication tower.

The height of your communication network is the maximum number of road hops needed to reach the farthest city from your tower location. Your goal is to minimize this maximum distance - find all possible tower locations that result in the smallest possible network height.

Return a list of all optimal tower locations (city labels) that minimize the communication network height.

Input & Output

example_1.py โ€” Basic Tree
$ Input: n = 4, edges = [[1,0],[1,2],[1,3]]
โ€บ Output: [1]
๐Ÿ’ก Note: Node 1 is connected to nodes 0, 2, and 3. When rooted at 1, all other nodes are at distance 1, giving height 1. Any other root would have height 2.
example_2.py โ€” Linear Tree
$ Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
โ€บ Output: [3,4]
๐Ÿ’ก Note: Both nodes 3 and 4 can serve as roots for minimum height trees. When rooted at either, the maximum distance to any node is 2.
example_3.py โ€” Single Node
$ Input: n = 1, edges = []
โ€บ Output: [0]
๐Ÿ’ก Note: With only one node, it must be the root, and the tree height is 0.

Visualization

Tap to expand
Tree Center Discovery ProcessStep 1: Initial Tree102345Leaves: 3, 4, 5โ†’Step 2: Remove Leaves102New Leaves: 0, 2Step 3: Remove New Leaves1CENTER FOUND!๐ŸŽฏ The center is the last remaining node after removing all outer layers
Understanding the Visualization
1
Build Graph
Create adjacency list and identify initial leaf nodes (degree = 1)
2
Remove Leaves
Remove all leaf nodes and update their neighbors' degrees
3
Find New Leaves
Neighbors of removed leaves may become new leaf nodes
4
Repeat
Continue until only 1-2 nodes remain - these are the centers
Key Takeaway
๐ŸŽฏ Key Insight: The center of a tree is found by repeatedly removing leaf nodes - it's like peeling layers of an onion to find the core. There can be at most 2 centers in any tree.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each node is processed exactly once, each edge is examined at most twice

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for adjacency list, degree array, and queue

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 2 ร— 104
  • edges.length == n - 1
  • 0 โ‰ค ai, bi < n
  • ai โ‰  bi
  • The given input is guaranteed to be a tree
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
28.7K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen