Minimum Height Trees — LeetCode 310 Python Solution
MediumDepth-First SearchBreadth-First SearchGraphTopological Sort
- Problem
- #310
- Pattern
- Topological Sort
- Reading time
- 4 min
- Source
- leetcode.com
The problem
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
Example
- Input
- n = 4, edges = [[1,0],[1,2],[1,3]]
- Output
- [1]
- Explanation
- As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Python solution
Python
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
g = [[] for _ in range(n)]
degree = [0] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
degree[a] += 1
degree[b] += 1
q = deque(i for i in range(n) if degree[i] == 1)
ans = []
while q:
ans.clear()
for _ in range(len(q)):
a = q.popleft()
ans.append(a)
for b in g[a]:
degree[b] -= 1
if degree[b] == 1:
q.append(b)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 310. Minimum Height Trees is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
On a study list
This problem is on Grind 75.
Frequently asked questions
- How hard is LeetCode 310. Minimum Height Trees?
- LeetCode 310. Minimum Height Trees is rated Medium on LeetCode.
- What is the time complexity of LeetCode 310. Minimum Height Trees?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 310. Minimum Height Trees?
- The Python solution on this page uses O(n), where n is the number of nodes auxiliary space.
- What topics does LeetCode 310. Minimum Height Trees cover?
- LeetCode 310. Minimum Height Trees is tagged Depth-First Search, Breadth-First Search, Graph and Topological Sort on LeetCode.