[LeetCode] 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]]
- 0
- |
- 1
- / \
- 2 3
return [1]
Example 2:
Given n = 6
, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
- 0 1 2
- \ | /
- 3
- |
- 4
- |
- 5
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.
Credits:
Special thanks to @peisi for adding this problem and creating all test cases.
Update (2015-11-25):
The function signature had been updated to return List<Integer>
instead of integer[]
. Please click the reload button above the code editor to reload the newest default code definition.
这道题虽然是树的题目,但是跟其最接近的题目是Course Schedule 课程清单和Course Schedule II 课程清单之二。由于LeetCode中的树的题目主要都是针对于二叉树的,而这道题虽说是树但其实本质是想考察图的知识,这道题刚开始在拿到的时候,我最先想到的解法是遍历的点,以每个点都当做根节点,算出高度,然后找出最小的,但是一时半会又写不出程序来,于是上网看看大家的解法,发现大家推崇的方法是一个类似剥洋葱的方法,就是一层一层的褪去叶节点,最后剩下的一个或两个节点就是我们要求的最小高度树的根节点,这种思路非常的巧妙,而且实现起来也不难,跟之前那到课程清单的题一样,我们需要建立一个图g,是一个二维数组,其中g[i]是一个一维数组,保存了i节点可以到达的所有节点。我们开始将所有只有一个连接边的节点(叶节点)都存入到一个队列queue中,然后我们遍历每一个叶节点,通过图来找到和其相连的节点,并且在其相连节点的集合中将该叶节点删去,如果删完后此节点也也变成一个叶节点了,加入队列中,再下一轮删除。那么我们删到什么时候呢,当节点数小于等于2时候停止,此时剩下的一个或两个节点就是我们要求的最小高度树的根节点啦,参见代码如下:
C++ 解法一:
- class Solution {
- public:
- vector<int> findMinHeightTrees(int n, vector<pair<int, int> >& edges) {
- if (n == ) return {};
- vector<int> res;
- vector<unordered_set<int>> adj(n);
- queue<int> q;
- for (auto edge : edges) {
- adj[edge.first].insert(edge.second);
- adj[edge.second].insert(edge.first);
- }
- for (int i = ; i < n; ++i) {
- if (adj[i].size() == ) q.push(i);
- }
- while (n > ) {
- int size = q.size();
- n -= size;
- for (int i = ; i < size; ++i) {
- int t = q.front(); q.pop();
- for (auto a : adj[t]) {
- adj[a].erase(t);
- if (adj[a].size() == ) q.push(a);
- }
- }
- }
- while (!q.empty()) {
- res.push_back(q.front()); q.pop();
- }
- return res;
- }
- };
Java 解法一:
- public class Solution {
- public List<Integer> findMinHeightTrees(int n, int[][] edges) {
- if (n == 1) return Collections.singletonList(0);
- List<Integer> leaves = new ArrayList<>();
- List<Set<Integer>> adj = new ArrayList<>(n);
- for (int i = 0; i < n; ++i) adj.add(new HashSet<>());
- for (int[] edge : edges) {
- adj.get(edge[0]).add(edge[1]);
- adj.get(edge[1]).add(edge[0]);
- }
- for (int i = 0; i < n; ++i) {
- if (adj.get(i).size() == 1) leaves.add(i);
- }
- while (n > 2) {
- n -= leaves.size();
- List<Integer> newLeaves = new ArrayList<>();
- for (int i : leaves) {
- int t = adj.get(i).iterator().next();
- adj.get(t).remove(i);
- if (adj.get(t).size() == 1) newLeaves.add(t);
- }
- leaves = newLeaves;
- }
- return leaves;
- }
- }
此题还有递归的解法(未完待续...)
类似题目:
参考资料:
https://discuss.leetcode.com/topic/30572/share-some-thoughts/2
https://discuss.leetcode.com/topic/67543/java-o-n-solution-with-explanation-dfs-twice-beat-95
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Minimum Height Trees 最小高度树的更多相关文章
- [LeetCode] 310. Minimum Height Trees 最小高度树
For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...
- LeetCode Minimum Height Trees
原题链接在这里:https://leetcode.com/problems/minimum-height-trees/ 题目: For a undirected graph with tree cha ...
- [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 ...
- 310. Minimum Height Trees -- 找出无向图中以哪些节点为根,树的深度最小
For a undirected graph with tree characteristics, we can choose any node as the root. The result gra ...
- 图论-BFS-最小高度的树 Minimum Height Trees
2018-09-24 12:01:38 问题描述: 对于一个具有树特征的无向图,我们可选择任何一个节点作为根.图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树.给出这样的一个图,写 ...
- [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 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS 相似题目 参考资料 日期 题目地址:http ...
- leetcode.310最小高度树
对于一个具有树特征的无向图,我们可选择任何一个节点作为根.图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树.给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点. ...
随机推荐
- 5.JAVA之GUI编程窗体事件
我们回顾下第三篇时的内容: 在3.JAVA之GUI编程Frame窗口中窗体是无法直接关闭的,想要关闭须进程管理器结束进程方式关掉. 现在我们就来解决下这个问题. ******************* ...
- ldap部署相关,ldap双机\LAM配置管理\ldap备份还原
前言 接之前我的文章,django+ldap+memcache实现单点登录+统一认证 就单点登录实现过程进行详细记录,ldap是一切的基础,可以把它理解成一个读强写弱的文件类型数据库,统一认证我们通过 ...
- Rafy 框架 - 使用 SqlTree 查询
本文介绍如何使用 Rafy 框架中的 Sql Tree 查询: 除了开发者常用的 Linq 查询,Rafy 框架还提供了 Sql 语法树的方式来进行查询. 这种查询方式下,开发者不需要直接编写真正的 ...
- c#面向对象基础技能——学习笔记(三)基于OOP思想研究对象的【方法】
实例方法:(解决问题的步骤)完成某功能的各种语句的组合 编写方法要考虑的内容: 1.通过项目需求,确定各方法的任务.功能: 2.方法的可访问性(默认是private):(字段private 属性int ...
- [Tool] Open Live Writer 插件更新
最新插件下载地址:Memento.OLW_V1.0.0.2.7z 零.历史更新记录 2016.11.24 1. 修正 cnblog 语法高亮中的 SQL.Perl 语法高亮异常 下载地址:Mement ...
- LINQ to SQL语句(14)之Null语义和DateTime
Null语义 说明:下面第一个例子说明查询ReportsToEmployee为null的雇员.第二个例子使用Nullable<T>.HasValue查询雇员,其结果与第一个例子相同.在第三 ...
- git push不用重复输入用户名和密码(解决方案)
每次git push都要输入用户名和密码,有点麻烦,就上网搜了下解决方案. 网上的解决方案有的讲得不清晰,逐个试了后,总结下两种有效的解决方案. 方案一: 1.在计算机安装盘(即一般为C盘)下找到 ...
- Eclipse Meaven Spring SpringMVC Mybaits整合
本示例是在:Ubuntu15上实现的:Windows上安装Maven将不太相同. Maven Install Run command sudo apt-get install maven, to in ...
- ASP.NET MVC4入门到精通系列目录汇总
序言 最近公司在招.NET程序员,我发现好多来公司面试的.NET程序员居然都没有 ASP.NET MVC项目经验,其中包括一些工作4.5年了,甚至8年10年的,许多人给我的感觉是:工作了4.5年,We ...
- Linux文件管理命令笔记
more\less:翻页命令 more:翻页的形式查看文件内容.该命令可作为管道命令. 翻页过程可使用的键: 空格(space):向下翻页: 回车(Enter):向下翻一行: b:往回翻,只限,但管道 ...