leetcode(310). Minimum Height Trees

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. 删除后的子问题的解和原来一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值