classSolution(object):deffindMinHeightTrees(self, n, edges):
res = [0for j in range(0, n)]
for k in range(0, n):
visit = [Falsefor j in range(0, n)]
defdfs(res,edges, n, i, level, visit):if(level>res[k]):
res[k] = level
visit[i] = Truefor j in range(0, len(edges)):
if (edges[j][0] == i andnot visit[edges[j][1]]):
dfs(res,edges, n, edges[j][1], level + 1, visit)
if (edges[j][1] == i andnot visit[edges[j][0]]):
dfs(res,edges, n, edges[j][0], level + 1, visit)
bfs(res,edges, n, k, 0, visit)
minheightIndex = [0]
for i in range(1, len(res)):
if (res[i] < res[minheightIndex[0]]):
minheightIndex = [i]
elif (res[i] == res[minheightIndex[0]]):
minheightIndex.append(i)
return minheightIndex
classSolution(object):deffindMinHeightTrees(self, n, edges):#initial
degreeZero = [i for i in range(0,n)]
while (True):
degree = [0for j in range(0, n)]
for i in range(len(edges)):
if(edges[i][0]!= -1):
degree[edges[i][0]] += 1
degree[edges[i][1]] += 1
degreeOne = []
zero = 0# find degree oneif(len(degreeZero) == 2ornot len(degreeZero)):
return degreeZero
for i in range(len(degree)):
if (degree[i] == 1):
degreeOne.append(i)
# update degreefor i in range(len(degreeOne)):
for j in range(len(edges)):
if (edges[j][0] == degreeOne[i] or edges[j][1] == degreeOne[i]):
degreeZero.remove(degreeOne[i])
edges[j][0] = -1
edges[j][1] = -1
import collections;
classSolution(object):deffindMinHeightTrees(self, n, edges):#initial#e:set of link nodeif n == 1: return [0]
e = collections.defaultdict(list)
for x,y in edges:
e[x].append(y)
e[y].append(x)
res = list(e.keys())
while(len(res)>2):
leaves = [x for x in e if len(e[x]) == 1]
for j in range (0,len(leaves)):
for y in range (0,len(e[leaves[j]])):
if(y == j):
e[y].remove(leaves[j])
del e[leaves[j]]
res.remove(leaves[j])
return res