[LeetCode] 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 :
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 exactly one 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.
Java:
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
    List<Integer> result = new ArrayList<Integer>();
    if(n==0){
        return result;
    }
    if(n==1){
        result.add(0);
        return result;
    }
    ArrayList<HashSet<Integer>> graph = new ArrayList<HashSet<Integer>>();
    for(int i=0; i<n; i++){
        graph.add(new HashSet<Integer>());
    }
    for(int[] edge: edges){
        graph.get(edge[0]).add(edge[1]);
        graph.get(edge[1]).add(edge[0]);
    }
    LinkedList<Integer> leaves = new LinkedList<Integer>();
    for(int i=0; i<n; i++){
        if(graph.get(i).size()==1){
            leaves.offer(i);
        }
    }
    if(leaves.size()==0){
        return result;
    }
    while(n>2){
        n = n-leaves.size();
        LinkedList<Integer> newLeaves = new LinkedList<Integer>();
        for(int l: leaves){
            int neighbor = graph.get(l).iterator().next();
            graph.get(neighbor).remove(l);
            if(graph.get(neighbor).size()==1){
                newLeaves.add(neighbor);
            }
        }
        leaves = newLeaves;
    }
    return leaves;
}  
Python:
class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
if n == 1:
return [0] neighbors = collections.defaultdict(set)
for u, v in edges:
neighbors[u].add(v)
neighbors[v].add(u) pre_level, unvisited = [], set()
for i in xrange(n):
if len(neighbors[i]) == 1: # A leaf.
pre_level.append(i)
unvisited.add(i) # A graph can have 2 MHTs at most.
# BFS from the leaves until the number
# of the unvisited nodes is less than 3.
while len(unvisited) > 2:
cur_level = []
for u in pre_level:
unvisited.remove(u)
for v in neighbors[u]:
if v in unvisited:
neighbors[v].remove(u)
if len(neighbors[v]) == 1:
cur_level.append(v)
pre_level = cur_level return list(unvisited)
C++:
// Time: O(n)
// Space: O(n) class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if (n == 1) {
return {0};
} unordered_map<int, unordered_set<int>> neighbors;
for (const auto& e : edges) {
int u, v;
tie(u, v) = e;
neighbors[u].emplace(v);
neighbors[v].emplace(u);
} vector<int> pre_level, cur_level;
unordered_set<int> unvisited;
for (int i = 0; i < n; ++i) {
if (neighbors[i].size() == 1) { // A leaf.
pre_level.emplace_back(i);
}
unvisited.emplace(i);
} // A graph can have 2 MHTs at most.
// BFS from the leaves until the number
// of the unvisited nodes is less than 3.
while (unvisited.size() > 2) {
cur_level.clear();
for (const auto& u : pre_level) {
unvisited.erase(u);
for (const auto& v : neighbors[u]) {
if (unvisited.count(v)) {
neighbors[v].erase(u);
if (neighbors[v].size() == 1) {
cur_level.emplace_back(v);
}
}
}
}
swap(pre_level, cur_level);
} vector<int> res(unvisited.begin(), unvisited.end());
return res;
}
};
类似题目:
Course Schedule II
Course Schedule
Clone Graph
All LeetCode Questions List 题目汇总
[LeetCode] 310. Minimum Height Trees 最小高度树的更多相关文章
- [LeetCode] Minimum Height Trees 最小高度树
		For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ... 
- [LeetCode] 310. Minimum Height Trees 解题思路
		For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ... 
- leetcode@ [310] Minimum Height Trees
		For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ... 
- 310. Minimum Height Trees -- 找出无向图中以哪些节点为根,树的深度最小
		For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ... 
- 【LeetCode】310. Minimum Height Trees 解题报告(Python)
		作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 相似题目 参考资料 日期 题目地址:http ... 
- 310. Minimum Height Trees
		For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ... 
- [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 ... 
- [Swift]LeetCode310. 最小高度树 | Minimum Height Trees
		For an undirected graph with tree characteristics, we can choose any node as the root. The result gr ... 
- 最小高度的树 Minimum Height Trees
		2018-09-24 12:01:38 问题描述: 问题求解: 毫无疑问的一条非常好的题目,采用的解法是逆向的BFS,也就是从叶子节点开始遍历,逐步向中心靠拢,最终留下的叶子节点就是答案. publi ... 
随机推荐
- C#操作域用户ADHelper
			在C#中操作域用户,在项目中写的帮助类: using System; using System.Collections.Generic; using System.DirectoryServices; ... 
- Centos7-安装py3
			安装依赖 yum install gcc openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel li ... 
- 读取yaml文件小方法
			def read_inf(inf_path): '''读取指定路径配置文件''' try: import yaml fr = open(inf_path) fy = yaml.load(fr) fr. ... 
- oracle plsql 实现apriori算法
			对apriori关联关系算法研究了一段时间,网上能搜到的例子,大部分是python写的,数据集长得像下面这样: [[I1,I2,I5],[I2,I4],[I2,I3],[I1,I2,I4],[I1,I ... 
- 8、Python简单数据类型(int、float、complex、bool、str)
			一.数据类型分类 1.按存值个数区分 单个值:数字,字符串 多个值(容器):列表,元组,字典,集合 2.按可变不可变区分 可变:列表[],字典{},集合{} 不可变:数字,字符串,元组().bool, ... 
- c#——ref 和 out 的区别
			一个用关键字 ref 标示,一个用 out 标示. 牵扯到数据是引用类型还是值类型. 一般用这两个关键字你是想调用一个函数将某个值类型的数据通过一个函数后进行更改.传 out 定义的参数进去的时候这个 ... 
- python面试题&练习题之嵌套循环
			1.打印如下结果: 1*5=5 2*10=20 3*15=45 ... 10*50=500 for i in range(1,11): print(str(i)+'x'+str((i*5))+'='+ ... 
- JS判断某变量是否为某数组中的一个值的3种方法
			1.正则表达式 js 中判断某个元素是否存在于某个 js 数组中,相当于 PHP 语言中的 in_array 函数. 1 Array.prototype.in_array = function (e) ... 
- Oracle iops测试
			DECLARE lat INTEGER; iops INTEGER; mbps INTEGER;BEGIN DBMS_RESOURCE_MANAGER.CALIBRATE_IO(4, 10, ... 
- puppeteer 试用
			puppeteer 是chrome 团队提供的Headless chrome node api 库,我们可以用来方便的进行chrome 操作,同时 可以做好多事情(web 爬虫,生成pdf,截图... ... 
