博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
拓扑排序应用(leetcode 310 python)
阅读量:4320 次
发布时间:2019-06-06

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

最小高度树

对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。

格式

该图包含 n 个节点,标记为 0 到 n - 1。给定数字 n 和一个无向边 edges 列表(每一个边都是一对标签)。

你可以假设没有重复的边会出现在 edges 中。由于所有的边都是无向边, [0, 1]和 [1, 0] 是相同的,因此不会同时出现在 edges 里。

示例 1:

输入: n = 4, edges = [[1, 0], [1, 2], [1, 3]]        0        |        1       / \      2   3 输出: [1]

示例 2:

输入: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]     0  1  2      \ | /        3        |        4        |        5 输出: [3, 4]

说明:

  •  根据,树是一个无向图,其中任何两个顶点只通过一条路径连接。 换句话说,一个任何没有简单环路的连通图都是一棵树。
  • 树的高度是指根节点和叶子节点之间最长向下路径上边的数量。
class Solution(object):    def findMinHeightTrees(self, n, edges):        """        :type n: int        :type edges: List[List[int]]        :rtype: List[int]        """        if edges == []:            return [0]        dic = {}        for i in range(len(edges)):            if edges[i][0] in dic:                dic[edges[i][0]].append(edges[i][1])            else:                dic[edges[i][0]] = []                dic[edges[i][0]].append(edges[i][1])            if edges[i][1] in dic:                dic[edges[i][1]].append(edges[i][0])            else:                dic[edges[i][1]] = []                dic[edges[i][1]].append(edges[i][0])        while len(dic) > 2:            temp = []            for key in dic:                if len(dic[key]) == 1:                    temp.append(key)            for i in range(len(temp)):                key = temp[i]                k = dic[key][0]                index = dic[k].index(key)                del dic[k][index]                dic.pop(key)        return list(dic.keys())

  

转载于:https://www.cnblogs.com/qkqBeer/articles/10207499.html

你可能感兴趣的文章
magento主页限制某个目录的产品显示数量
查看>>
SpringBoot整合Netty
查看>>
MongoDB数据库的基本操作
查看>>
PAT乙级1014
查看>>
ORACLE wm_concat自定义
查看>>
[Zend PHP5 Cerification] Lectures -- 6. Database and SQL
查看>>
[Drupal] Using the Administrator theme whenever you want.
查看>>
【Hibernate框架】关联映射(一对一关联映射)
查看>>
【算法】大数乘法
查看>>
WPF解析PPT为图片
查看>>
JavaScrict中的断言调试
查看>>
密码服务
查看>>
结构体在内存中的存储
查看>>
冲刺阶段—个人工作总结01
查看>>
基于Python的Webservice开发(二)-如何用Spyne开发Webservice
查看>>
PowerDesigner修改设计图中文字的字体大小等样式
查看>>
Python list和 np.Array 的转换关系
查看>>
jenkins忘记密码如何处理?
查看>>
布尔操作符-逻辑或(||)
查看>>
vim的列编辑操作
查看>>