LeetCode 310. Minimum Height Trees
考点 | 难度 |
---|---|
Tree | Medium |
题目
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]])