Problem
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.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
1
/ \
2 - 3
Example 2:
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
| |
4 - 3
Note:
- The size of the input 2D-array will be between 3 and 1000.
- Every integer represented in the 2D-array will be between 1 and N, where N is the
size of the input array.
解题思路
这一题一开始可以考虑一次从每一个结点出发,并将其作为根节点,然后依次遍历每一条边,判断边的节点是不是都在树中,如果都在树中,则返回就好。这种方法直观,但是时间复杂度太高,不实用。因此这里我们考虑使用并查集的方法。
我们使用一个数组来保存每一个节点的直接相连的父节点,开始时每一个节点都是自己的父节点,然后遍历给出的每一条边,对每一个边的端点,一直在数组中回溯查找该端点的根节点,如果这两个端点的对应的根节点相同,说明,这两个端点处在同一棵树中,反之则不在同一棵树中。当不在同一棵树中时,将其中一棵树的根节点指向另一棵树的根节点,相当于将两棵树合并成了一棵树。
代码如下:
class Solution:
def findRedundantConnection(self, edges) -> list:
parent = [i for i in range(len(edges) + 1)]
for s, e in edges:
root1, dis1 = self.get_root(parent, s)
root2, dis2 = self.get_root(parent, e)
if root1 == root2:
return [s, e]
if dis1 < dis2:
parent[root1] = root2
else:
parent[root2] = root1
def get_root(self, parent, node):
"""
:param parent:
:param node:
:return: root and distance
"""
dis = 0
while parent[node] != node:
node = parent[node]
dis += 1
return node, dis
g e t _ r o o t get\_root get_root函数用于计算节点的根节点,并返回两个数值,第一个数值表示根节点的编号,第二个数值表示节点到根节点的距离。当两个端点所对应的树不同时,我们判断节点的距离,并将距离短的作为距离长的的一棵子树,这样可以优化树的结构,不至于树深度过大。