""" 时间复杂度 O(n) """ n = 11 edges = [[0,1],[0,2],[2,3],[0,4],[2,5],[5,6],[3,7],[6,8],[8,9],[9,10]] class Solution(object): def findMinHeightTrees(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[int] """ if n == 1: return [0] d = {} s = {} h = {} res = [0] for e in edges: v1, v2 = e[0], e[1] if d.get(v1, -1) == -1: d[v1] = [] d[v1].append(v2) if d.get(v2, -1) == -1: d[v2] = [] d[v2].append(v1) s[v1] = s[v2] = -1 s[0] = 1 self.DFS(0, d, s, h) s[0] = -1 res = self.getMin(0, d, h, s, 0, h[0]-1, res) return res def DFS(self, n, d, s, h): m = 1 for v in d[n]: if s[v] != 1: s[v] = 1 m = max(m, self.DFS(v, d, s, h)+1) h[n] = m return m def getMin(self, n, d, h, s, min, height, res): max1 = 0 max2 = 0 i = -1 for v in d[n]: if s[v] != -1: s[v] = -1 if h[v] > max1: max2 = max1 max1 = h[v] i = v elif h[v] > max2: max2 = h[v] max2 = max(min, max2) if i == -1: return res temp = max(max1-1, max2+1) if temp > height: return res elif temp == height: res.append(i) else: res = [] res.append(i) height = temp res = self.getMin(i, d, h, s, max2+1, height, res) return res
|