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:

  • According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactlyone path. In other words, any connected graph without simple cycles is a tree.”
  • The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

这个题目思路来自于Solution, 类似于剥洋葱, 从leaves开始一层一层往里面剥, 依次更新leaves, 到最后只剩一个或2个nodes的时候(因为根据tree的定义, 从数学上可以证明最多只有两个root的height一样), 那么剩下的点就是答案.

1. Constraints

1) 题目意思已经很清楚了, 只是需要判断edge case: n = 1, n= 2 时

2. Ideas

类似于BFS的解法      T: O(n)    S: O(n)

3. Code

class Solution:
def miniHeightTree(self, n, edges):
if n <3: return [i for i in range(n)]
graph = collections.defaultdict(set)
for c1, c2 in edges:
graph[c1].add(c2)
graph[c2].add(c1)
leaves = [i for i in range(n) if len(graph[i]) == 1]
while n > 2:
n -= len(leaves)
newleaves = []
for i in leaves: #take off the outside leaves
neig = graph[i].pop() # neighbour of the leave
graph[neig].remove(i) #remove the edge from leave to neighbor
if len(graph[neig]) == 1:
newleaves.append(neig)
leaves = newleaves
return leaves

[LeetCode] 310. Minimum Height Trees_Medium tag: BFS的更多相关文章

  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. 【LeetCode】310. Minimum Height Trees 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 相似题目 参考资料 日期 题目地址:http ...

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

    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] 64. Minimum Path Sum_Medium tag: Dynamic Programming

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...

  8. [LeetCode] 127. Word Ladder _Medium tag: BFS

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  9. [LeetCode] 301. Remove Invalid Parentheses_Hard tag:BFS

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...

随机推荐

  1. Repeater嵌套绑定Repeater以及内层调用外层数据

    aspx: <table border=" style="margin-bottom: 5px" width="100%"> <as ...

  2. 对Array进行排序(按字母顺序)

    通过使用java.utils.Arrays.sort()和String.CASE_INSENSITIVE_OREDR,可以很容易的对结果进行排序(按字母顺序): String[] array = { ...

  3. cmake编译android平台的libPoco

    1.下载源代码,解压到POCO-1.7.8-ALL 2.从$ANDROID_NDK\cmake下复制android.toolchain.cmake AndroidNdkGdb.cmake Androi ...

  4. 简易扩展Visual Studio UnitTesting支持TestMethodCase

    NUnit的TestCaseAttribute可以简化大量的测试参数输入用例的编写,如果基于Visual Studio Unit Test Project开发则默认没有类似的功能,看一段对比代码: p ...

  5. Log4net配置之Winform项目

    具体方法如下: 一.App.config配置 <?xml version="1.0" encoding="utf-8" ?> <configu ...

  6. HTML中块级元素与内联元素有什么区别 ?

    块级元素:默认宽度是100%(继承自父元素),如果块对象没有采用“float:left”或“float:right;”的样式,相邻的两个块对象就会分排在不同的两行上.例如,div, p, h1, fo ...

  7. Spark2 Dataset聚合操作

    data.groupBy("gender").agg(count($"age"),max($"age").as("maxAge&q ...

  8. 使用SQL手动创建数据库并创建一个具有该数据库所有权限的用户

    $ mysql -u adminusername -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. ...

  9. Pandas的concat方法

    在此我用的concat作用是加入新的记录,存储数据来用过的,不知道数据量大时候,效率会怎样 # 使用pandas来保存数据 df1 = pd.DataFrame([poem], columns=['p ...

  10. 添加用户username到sudo组

    添加用户username到sudo组: usermod -aG sudo username USERMOD(8) 系统管理命令 USERMOD(8) 名 usermod - 修改一个用户账户 大 us ...