LeetCode 310. 最小高度树(广度优先遍历)

题目描述

对于一个具有树特征的无向图,我们可选择任何一个节点作为根。图因此可以成为树,在所有可能的树中,具有最小高度的树被称为最小高度树。给出这样的一个图,写出一个函数找到所有的最小高度树并返回他们的根节点。
格式
该图包含 n 个节点,标记为 0 到 n - 1。给定数字 n 和一个无向边 edges 列表(每一个边都是一对标签)。
你可以假设没有重复的边会出现在 edges 中。由于所有的边都是无向边, [0, 1]和 [1, 0] 是相同的,因此不会同时出现在 edges 里。

在这里插入图片描述

思路

详见链接

代码

class Solution:
	def findMinHeightTrees(self, n:int, edges:List[List[int]])->List[int]:
		from collections import defaultdict
		if not edges:
			return [0]
		graph = defaultdict(list)
		for x,y in edges:
			graph[x].append(y)
			graph[y].append(x)
		leaves = [i for i in graph if len(graph[i]) == 1]
		while n > 2:
			n -= len(leaves)
			next_leaves = []
			for leave in leaves:
				tmp = graph[leave].pop()
				graph[tmp].remove(leave)
				if len(graph[tmp]) == 1:
					next_leaves.append(tmp)
			leaves = next_leaves
		return list(leaves)
发布了80 篇原创文章 · 获赞 239 · 访问量 7068

猜你喜欢

转载自blog.csdn.net/weixin_37763870/article/details/104547596