[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 ...
随机推荐
- Sql 数据库 用户密码MD5加密
直接给代码先 DECLARE @TAB TABLE( NAEM VARCHAR(50) ) DECLARE @PA VARCHAR(50) DECLARE @A VARCHAR(10) SET @A= ...
- 10. vue-router命名路由
命名路由的配置规则 为了更加方便的表示路由的路径,可以给路由规则起一个别名, 即为"命名路由". const router = new VueRouter ({ routes: [ ...
- 英语听力,如何成为更好的交谈着https://www.bilibili.com/video/av4279405?from=search&seid=5889429711390689339
and how many of you know at least one person that you because you just do not want to talk to them.y ...
- Greenplum 与 PostgreSQL 修改元数据(catalog)的方法 allow_system_table_mods
背景 PostgreSQL大量的信息保存在元数据中,所有的元数据都是内部维护的,例如建表.建索引.删表等操作,自动维护元数据. 在某些迫不得已的情况下才可能需要直接对元数据进行修改. 默认情况下,用户 ...
- Angular2发送HTTP请求SpringBoot后台跨域问题解决
Angular通过http发送post请求至SpringBoot的Controller,由于同源策略的保护,遇到跨域问题: • 源(origin)就是协议(http).域名(localhost)和端口 ...
- vue-cli3整体迁移至服务端渲染nuxtjs
vue项目与nuxt.js实在有着太多的不同,例如项目结构变化很大,router.js没了,vuex store写法有变化,router钩子没了等等.老项目毕竟也有一些体量,这么折腾我可接受不了,不过 ...
- mac 下的 tree 命令 终端展示你的目录树结构
相信很多使用过Linux的用户都用过tree命令,它可以像windows的文件管理器一样清楚明了的显示目录结构.mac 下使用 brew包管理工具安装 tree 前提:安装了homebrew(安装指令 ...
- React_02_ECMAScript6
1.let与const ES2015(ES6) 新增加了两个重要的 JavaScript 关键字: let 和 const. let 声明的变量只在 let 命令所在的代码块内有效,const 声明一 ...
- [内网渗透]Windows中的用户帐户与组账户
0x01 用户帐户 1.1 简介 用户帐户是对计算机用户身份的标识,本地用户帐户.密码存在本地计算机上,只对本机有效,存储在本地安全帐户数据库 SAM 中. 文件路径:C: ...
- D3.js的v5版本入门教程(第十一章)——交互式操作
D3.js的v5版本入门教程(第十一章) 与图形进行交互操作是很重要的!所谓的交互操作也就是为图形元素添加监听事件,比如说当你鼠标放在某个图形元素上面的时候,就会显示相应的文字,而当鼠标移开后,文字就 ...