LeetCode知识点总结 - 310

LeetCode 310. Minimum Height Trees

考点难度
TreeMedium
题目

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.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).

Return a list of all MHTs’ root labels. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

思路

https://leetcode.com/problems/minimum-height-trees/discuss/1631179/C%2B%2BPython-3-Simple-Solution-w-Explanation-or-Brute-Force-%2B-2x-DFS-%2B-Remove-Leaves-w-BFS
longest path里的中间的node,答案是longest path的一半(最多可能有两个值)

答案
class Solution:
    def findMinHeightTrees(self, n, E):
        G, seen = defaultdict(set), [False]*n
        for u,v in E:
            G[u].add(v)
            G[v].add(u)

        def dfs(i):
            if seen[i]: return []
            longest_path = []
            seen[i] = True
            for adj in G[i]:
                if not seen[adj]:
                    path = dfs(adj)
                    if len(path) > len(longest_path):
                        longest_path = path
            longest_path += [i]
            seen[i] = False
            return longest_path

        path = dfs(dfs(0)[0])
        return set([path[len(path)//2], path[(len(path)-1)//2]])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值