题目描述
Category:Medium Tree
In this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
题目理解
在本题中,树是一个无向图,是连通的,但是没有循环。
给定的输入是一个图,它开始是一个有N个节点的树(具有不同的值1、2、…, N),增加了一条额外的边。添加的边有两个从1到N的不同顶点,并且不是已经存在的边。
结果图是一个二维的边数组。每个边的元素都是一对[u, v]和u < v,表示连接节点u和v的无向边。
返回一条可以删除的边,这样得到的图就是一个有N个节点的树。如果有多个答案,则返回给定二维数组中最后出现的答案。答案边[u, v]应该是相同的格式,u < v。
解题思路
并查集
实现了并查集查找根节点的代码,并且做了路径压缩,防止树太高导致查找根节点缓慢。
https://blog.csdn.net/fuxuemingzhu/article/details/80487064
无法静下心来看于是先放上补充链接叭
花花酱 并查集
class Solution:
# Runtime: 52ms 87.35% MemoryUsage: 14.1MB 28.57%
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
tree = [-1] * (len(edges) + 1)
for edge in edges:
a = self.findRoot(edge[0], tree)
b = self.findRoot(edge[1], tree)
if a != b:
tree[a] = b
else:
return edge
def findRoot(self, x, tree):
if tree[x] == -1:
return x
else:
root = self.findRoot(tree[x], tree)
tree[x] = root
return root
这道题有点不太走心了 等我状态好的时候静下心来再战!
Time
2020.3.27 一道题写了一天 头秃