310. Minimum Height Trees

问题描述

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.
Example 1:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
return [3, 4]
Hint:
How many MHTs can a graph have at most?
Note:
(1) According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

问题分析

参考了LeetCode的Disccuss
Hint: 答案只可能有一个或两个节点。思路为依次删除叶子节点,剩下的1/2个节点即为解。
速度问题:如果每次遍历选出叶子节点,速度比较慢,可以每次删除当前叶子节点时,将新的叶子节点记录下来。

AC代码

class Solution(object):
    def findMinHeightTrees(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        if n == 1:
            return [0]
        neighbor = [set() for i in range(n)]
        for p,q in edges:
            neighbor[p].add(q)
            neighbor[q].add(p)
        
        leaves = [x for x in range(n) if len(neighbor[x]) == 1]

        while n > 2:
            n -= len(leaves)
            newLeaves = []
            for p in leaves:
                q = neighbor[p].pop()
                neighbor[q].remove(p)
                if len(neighbor[q]) == 1:
                    newLeaves.append(q)
            leaves = newLeaves
        return leaves

Runtime: 116 ms which beats 82.55% of Python submissions.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,792评论 0 33
  • 世界好奇妙,它将物以类聚,人以群分……形成七彩不同的“圈子”,周而复始的循环往复着! 它们看似都遵循...
    88兰猫阅读 591评论 0 4
  • 工作总结的开头对于一份工作总结的整体而言非常重要。工作总结开头怎么写呢?若每年都是老生常谈,永恒不变的格式,不免自...
    简明估阅读 2,194评论 0 19
  • 业界资深人,家具设计师+软装设计师 双料 打算玩这个 有人赏脸么?小众的垂直行业覆盖
    纹物阅读 264评论 0 1
  • 躺在床上 总感觉在风中行走 收割后的田野空旷而忧郁 厌倦雨...
    杨云涛阅读 449评论 3 3