-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0310-minimum-height-trees.py
More file actions
31 lines (27 loc) · 952 Bytes
/
0310-minimum-height-trees.py
File metadata and controls
31 lines (27 loc) · 952 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# time complexity: O(|V|)
# space complexity: O(|V|)
from typing import List
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2:
return [i for i in range(n)]
neighbors: List[set] = [set() for i in range(n)]
for start, end in edges:
neighbors[start].add(end)
neighbors[end].add(start)
leaves = []
for i in range(n):
if len(neighbors[i]) == 1:
leaves.append(i)
remainNodes = n
while remainNodes > 2:
remainNodes -= len(leaves)
newLeaves = []
while leaves:
leaf = leaves.pop()
neighbor = neighbors[leaf].pop()
neighbors[neighbor].remove(leaf)
if len(neighbors[neighbor]) == 1:
newLeaves.append(neighbor)
leaves = newLeaves
return leaves