尝试使用bfs解决,但是TLE。给出代码如下:
1 import sys 2 class Solution: 3 def __init__(self): 4 self.depth = [] 5 self.mindepth = sys.maxsize 6 7 def bfs(self,n,visited,l,root,count,dic): 8 while len(l) != 0: 9 temp = [] 10 while len(l) != 0: 11 cur = l.pop() 12 for e in dic[cur]: 13 if visited[e] == 0: 14 count += 1 15 visited[e] = 1 16 temp.append(e) 17 self.depth[root] += 1 18 if self.depth[root] > self.mindepth: 19 return 20 if len(temp) > 0 and count < n: 21 l = temp[:] 22 23 def findMinHeightTrees(self, n: int, edges: 'List[List[int]]') -> 'List[int]': 24 if len(edges) == 0: 25 return [0] 26 self.depth = [0] * n 27 result = [] 28 dic = {} 29 for i in range(len(edges)): 30 begin,end = edges[i][0],edges[i][1] 31 if begin not in dic: 32 dic[begin] = [end] 33 else: 34 dic[begin].append(end) 35 if end not in dic: 36 dic[end] = [begin] 37 else: 38 dic[end].append(begin) 39 40 for i in range(n): 41 visited = [0] * n 42 visited[i] = 1 43 self.bfs(n,visited,[i],i,1,dic) 44 if self.depth[i] < self.mindepth: 45 self.mindepth = self.depth[i] 46 for i in range(n): 47 if self.depth[i] == self.mindepth: 48 result.append(i) 49 return result
感觉需要使用缓存机制来加速,但做本题连续思考了差不多2个小时,脑力不足以继续解决本问题了。
还是参考一下别人的解决思路吧:
1 from collections import defaultdict 2 class Solution: 3 def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 4 if n == 1: 5 return [0] 6 7 degree = [0]*n 8 my_graph = defaultdict(list) 9 for n_l, n_r in edges: 10 my_graph[n_l].append(n_r) 11 my_graph[n_r].append(n_l) 12 degree[n_l] += 1 13 degree[n_r] += 1 14 frontier = [i for i in range(n) if degree[i] == 1] 15 16 while frontier: 17 nxt_step = [] 18 for n in frontier: 19 #degree[n] -= 1 20 for nx in my_graph[n]: 21 degree[nx] -= 1 22 if degree[nx] == 1: 23 nxt_step.append(nx) 24 if not nxt_step: 25 return frontier 26 frontier = nxt_step