-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.py
More file actions
31 lines (25 loc) · 863 Bytes
/
Solution.py
File metadata and controls
31 lines (25 loc) · 863 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
from typing import List
from collections import defaultdict
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
adj_list = defaultdict(list)
for u, v in edges:
adj_list[u].append(v)
adj_list[v].append(u)
leaves = [node for node in range(n) if len(adj_list[node]) == 1]
while n > 2:
n -= len(leaves)
new_leaves = []
for leaf in leaves:
neighbor = adj_list[leaf].pop()
adj_list[neighbor].remove(leaf)
if len(adj_list[neighbor]) == 1:
new_leaves.append(neighbor)
leaves = new_leaves
return leaves
n = 4
edges = [[1,0],[1,2],[1,3]]
sol = Solution()
print(sol.findMinHeightTrees(n, edges))