Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Hint:
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
According to the definition of tree on Wikipedia: “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.”
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
总结
此题用Union Find最简便,DFS 和 BFS 都可以。
解法1: DFS
按照题目意思,这是一个undirectedgraph判定是否是tree的问题,那么一个无向图要满足两个条件。一个是要全连通,另一个是要没有环。
基本思想是用DFS遍历,如果遍历到之前遇过的节点说明有环。遍历之后如果还有没有遍历过的节点那么就不是全通图。
Java
解法2: BFS
BFS 的思想和DFS的基本一致。要注意的是,在存储图的信息的时候,用一个Set比较方便。因为之后当我们在扫描一个节点连接的节点时,要删除对应节点中的edge(就是a连向b,那么b的相连node中一定有a,为了避免出现再遇到a,需要把对应的a从b相连的节点的list中删除,用set比较方便的解决此问题)
同时用一个set来维护已经访问过的节点。
Java
解法3: Union Find
Union Find的算法就不详述了。Union Find很适合来解决Graph找circle的问题。 这里的思路是如果两个node同属于一个parent那么就有circle存在。
如果不属于同一个parent,那么就把他们union起来成为一个group.
要注意的是最后如果没有出现circle,要比较一下是否每一个node都连接起来了,用edges.length == n - 1就可以判断
Java