-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path310_minimum-height-trees.py
66 lines (46 loc) · 1.9 KB
/
310_minimum-height-trees.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# https://leetcode.com/problems/minimum-height-trees/
from collections import deque
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if len(edges) == 0:
return [0]
adj_list = [set() for _ in range(0,n)]
for start, end in edges:
adj_list[start].add(end)
adj_list[end].add(start)
leaves = deque(leaf for leaf, neighbors in enumerate(adj_list) if len(neighbors) == 1)
remaining = n
while remaining > 2:
next_leaves = deque()
while len(leaves) > 0:
leaf = leaves.popleft()
neighbor = adj_list[leaf].pop()
adj_list[neighbor].remove(leaf)
if len(adj_list[neighbor]) == 1:
next_leaves.append(neighbor)
remaining -= 1
leaves = next_leaves
return list(leaves)
def findMinHeightTreesInefficient(self, n: int, edges: List[List[int]]) -> List[int]:
res = None
res_min = 2 * (10 ** 4) + 1
# adjecency list for e1-e2, undirected
adj_list = [[] for x in range(0,n)]
for e1, e2 in edges:
adj_list[e1].append(e2)
adj_list[e2].append(e1)
visited = None
def dfs(node):
visited.add(node)
# contains subproblem solutions
local_res = [0] + [dfs(next_node) + 1 for next_node in adj_list[node] if next_node not in visited]
return max(local_res)
for x in range(n):
visited = set()
ret = dfs(x)
if ret < res_min:
res = []
res_min = ret
if ret == res_min:
res.append(x)
return res