作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/minimum-height-trees/description/

题目描述

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 :

Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
|
1
/ \
2 3 Output: [1]

Example 2 :

Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
\ | /
3
|
4
|
5 Output: [3, 4]

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.

题目大意

找出以哪些节点为根节点的时候,构建出来的整棵树的高度是最低的。

解题方法

BFS

这个题很优秀啊,是个好题。这个题给定的是个图,但是让我们构建成树,也就是说构建出来的并不是二叉树。题目其实想考我们的是,整个图最靠近中间的节点是什么。我们使用类似与拓扑排序的BFS进行解决。

拓扑排序我们都知道,每次选择入度为0的节点进行删除。在这个题中,因为我们要找到无向图最靠近中间的节点,所以,我们先使用一个字典保存每个节点的所有相邻节点set。每次把所有只有一个邻接的节点(叶子节点,类似于入度为0,但是这是个无向图,入度等于出度)都放入队列,然后遍历队列中的节点u,把和每个节点u相邻的节点v的set删去u,所以这一步操作得到的是去除了叶子节点的新一轮的图。所以我们需要再次进行选择只有一个邻接节点的叶子节点,然后放入队列中,再次操作。最后结束的标准是,整个图只留下了1个或者两个元素。为什么不能是3个呢?因为题目第一句话说了给出的图是具有树的特性的,所以一定没有环存在。

这个题整体的思路就是把所有的叶子节点放入队列中,然后同时向中间遍历,这样最后剩下来的就是整棵树中间的元素。

时间复杂度是O(V),空间复杂度是O(E + V).

class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
if n == 1: return [0]
leaves = collections.defaultdict(set)
for u, v in edges:
leaves[u].add(v)
leaves[v].add(u)
que = collections.deque()
for u, vs in leaves.items():
if len(vs) == 1:
que.append(u)
while n > 2:
_len = len(que)
n -= _len
for _ in range(_len):
u = que.popleft()
for v in leaves[u]:
leaves[v].remove(u)
if len(leaves[v]) == 1:
que.append(v)
return list(que)

相似题目

207. Course Schedule
210. Course Schedule II

参考资料

http://www.cnblogs.com/grandyang/p/5000291.html

日期

2018 年 10 月 30 日 —— 啊,十月过完了

【LeetCode】310. Minimum Height Trees 解题报告(Python)的更多相关文章

  1. [LeetCode] 310. Minimum Height Trees 解题思路

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  2. [LeetCode] 310. Minimum Height Trees 最小高度树

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  3. leetcode@ [310] Minimum Height Trees

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  4. 310. Minimum Height Trees

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  5. [LeetCode] 310. Minimum Height Trees_Medium tag: BFS

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  6. 310. Minimum Height Trees -- 找出无向图中以哪些节点为根,树的深度最小

    For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...

  7. 【LeetCode】1051. Height Checker 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 排序比较 日期 题目地址:https://leetc ...

  8. 【LeetCode】872. Leaf-Similar Trees 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 中序遍历 先序遍历 后序遍历 日期 题目地址:htt ...

  9. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

随机推荐

  1. Bebug与Release版本

    如果调试过程无调试信息,检查编译选项是否切换到了release下 比如Cfree5等编译器 ms为了方便调试才诞生了DEBUG版. 这也导致了MFC有两个功能一至但版本不同的类库,一个为DEBUG版, ...

  2. 关于SQL中Union和Join的用法

    转自帘卷西风的专栏(http://blog.csdn.net/ljxfblog) https://blog.csdn.net/ljxfblog/article/details/52066006 Uni ...

  3. 详解工作流框架Activiti的服务架构和组件

    摘要:通过这篇文章,可以对工作流有一个基本的认识,为后续工作流框架Activiti的学习打下坚实的基础. 本文分享自华为云社区<BPMN工作流的基本概念!详解工作流框架Activiti的服务架构 ...

  4. A Child's History of England.22

    CHAPTER 8 ENGLAND UNDER WILLIAM THE FIRST, THE NORMAN CONQUEROR Upon the ground where the brave Haro ...

  5. mystar01 nodejs MVC 公共CSS,JS设置

    mystar01 nodejs MVC gulp 项目搭建 config/express.js中定义别名 //将下载的第三方库添加到静态资源路径当中,方便访问 app.use('/jquery', e ...

  6. How exactly does Google AdWords work?

    The key to how Google AdWords works is the Quality Score. Quality Score is generally how well an ad ...

  7. HashMap 和 HashSet

    对于HashSet而言,系统采用Hash算法决定集合元素的存储位置,这样可以保证快速存取集合元素: 对于HashMap,系统将value当成key的附属,系统根据Hash算法来决定key的存储位置,这 ...

  8. 【Java 基础】Collectors 使用小结

    Collectors 与集合转换 Collectors toList streamArr.collect(Collectors.toList()); List<Integer> colle ...

  9. 【C/C++】习题3-4 周期串/算法竞赛入门经典/数组和字符串

    [题目] 如果某个字符串可以由长度为k的字符串重复多次得到,则称该串以k为周期. 输入一个长度不超过80的字符串,输出最小周期. [思路] 暴力求解.依次考察周期1~长度n. 筛选:周期一定是长度n的 ...

  10. IT过来人的10点经验谈

    1 入行要趁早,正常是22岁本科或25岁硕士毕业入行.如果是零基础经培训班加持的,尽量在28岁前入行,30岁以后再想要入行IT的,千万慎重. 2 IT行业确实能挣大钱,而且能为学历一般学校一般家庭背景 ...