leetcode -- Minimum Height Trees -- 关于graph的,重点

本文介绍了一种寻找图中最小高度树的有效算法。通过逐步移除叶子节点的方式找到树的根节点,适用于解决LeetCode上的Minimum Height Trees问题。文章详细解释了算法原理,并提供了Python实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/minimum-height-trees/

有trick
对graph不熟悉。再看几遍。

参考http://bookshadow.com/weblog/2015/11/26/leetcode-minimum-height-trees/

基本思路是“逐层删去叶子节点,直到剩下根节点为止”

有点类似于拓扑排序

最终剩下的节点个数可能为1或者2

时间复杂度:O(n),其中n为顶点的个数。

记住这些结论以及这样的code怎么写就行了。就跟拓扑排序一样,逐次去掉leaf node

class Solution(object):
    def findMinHeightTrees(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        children = collections.defaultdict(set)
        for s, t in edges:#记录edge
            children[s].add(t)
            children[t].add(s)
        vertices = set(children.keys())
        while len(vertices) > 2:
            leaves = [x for x in children if len(children[x]) == 1]
            for x in leaves:
                for y in children[x]:
                    children[y].remove(x)
                del children[x]
                vertices.remove(x)
        return list(vertices) if n != 1 else [0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值