problem
For a undirected graph with tree characteristics, we can choose any
node as the root. The result graph is then a rooted tree. Among all
possible rooted trees, those with minimum height are called minimum
height trees (MHTs). Given such a graph, write a function to find all
the MHTs and return a list of their root labels.Format The graph contains n nodes which are labeled from 0 to n - 1.
You will be given the number n and a list of undirected edges (each
edge is a pair of labels).You can assume that no duplicate edges will appear in edges. Since all
edges are undirected, [0, 1] is the same as [1, 0] and thus will not
appear together in edges.
分析
中文描述:给定一个节点数为n,边数为n-1的连通图,求出把那些节点看做根所形成的树深度最小。
这个问题可以抽象成求某一个节点在图中最远的距离。
O(n3)
:使用Floyd算法求出任意两节点的最短路径,然后可求出上述问题。
O(n3) :对一个节点进行广度优先搜素时可以记录下距离它最远的节点距离,对所有的节点进行这样的操作即可求出答案。
O(n) :每次删除所有叶节点,返回删除时的最后一批节点。
class Solution(object):
def findMinHeightTrees(self, n, edges):
if n == 1: return [0]
adj = [set() for _ in xrange(n)]
for i, j in edges:
adj[i].add(j)
adj[j].add(i)
leaves = [i for i in xrange(n) if len(adj[i]) == 1]
while n > 2:
n -= len(leaves)
newLeaves = []
for i in leaves:
j = adj[i].pop()
adj[j].remove(i)
if len(adj[j]) == 1: newLeaves.append(j)
leaves = newLeaves
return leaves
总结
类似于数组主元素的删除法,这种类似的算法都满足:
1. 被删除的元素肯定不是result,
2. 删除后的子问题性质和原来一样
3. 删除后的子问题的解和原来一样