博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode Minimum Height Trees
阅读量:4696 次
发布时间:2019-06-09

本文共 2054 字,大约阅读时间需要 6 分钟。

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 = 4edges = [[1, 0], [1, 2], [1, 3]]

0        |        1       / \      2   3

return [1]

Example 2:

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

0  1  2      \ | /        3        |        4        |        5

return [3, 4]

题意:

给定一个n个结点n-1条边的无向图(就是树啦),让你找从哪个点出发,到其他结点的最长距离最小?(返回所有答案)

思路:

一开始类似RIP来更新距离,结果TLE。证明O(n^2)的复杂度太大

只好想其他的方法。

答案一定是最长距离的中间结点位置上。

我们要的是中间结点,沿着树的外围每次把叶子结点砍掉,那么,最后剩下的不就是中间结点了么?

# leetcode Minimum Height Trees# http://www.hrwhisper.me/leetcode-minimum-height-trees/class Solution(object):    def findMinHeightTrees(self, n, edges):        """        :type n: int        :type edges: List[List[int]]        :rtype: List[int]        """        if n==1: return [0]        digree = [0 for i in xrange(n)]        g = [[] for i in xrange(n)]        for x,y in edges:            digree[x] += 1            digree[y] += 1            g[x].append(y) #add_edge            g[y].append(x)        leaves = [i for i in xrange(n) if digree[i]==1]        nodes = n        while nodes > 2:            temp = []            for i in leaves:                digree[i] = 0                nodes -= 1                for j in g[i]:                    digree[j] -= 1                    if digree[j] == 1:                        temp.append(j)            leaves = temp        return leaves

本文地址(就是我的新blog):
本文由  原创发布,转载请点名出处

转载于:https://www.cnblogs.com/murmured/p/5004015.html

你可能感兴趣的文章
Web Service数据源
查看>>
php.ini详解(转)
查看>>
[转]基于Python的接口测试框架
查看>>
"ORA-00942: 表或视图不存在 "的原因和解决方法[转]
查看>>
PeekMessage、GetMessage的区别
查看>>
磁盘使用率达到100%
查看>>
linux跳过root密码登陆
查看>>
mini2440 U-boot 编译
查看>>
在UTF-8中,一个汉字为什么需要三个字节?
查看>>
学习ThreadLocal
查看>>
在 Visual Studio 调试器中指定符号 (.pdb) 和源文件
查看>>
直接量
查看>>
leetcode 115. 不同的子序列(Distinct Subsequences)
查看>>
三元表达式
查看>>
Go初接触之libjpeg-turbo
查看>>
UVa 11300 Spreading the Wealth 分金币
查看>>
[leetcode] Happy Number
查看>>
Java第五周学习总结
查看>>
j.c.Warnsdorff马踏棋盘算法
查看>>
the openning
查看>>