Graph Valid Tree
Medium
Question
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.
Notice
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.
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.
Tags
Depth First Search Facebook Zenefits Union Find Breadth First Search Google
Related Problems
Medium Find the Connected Component in the Undirected Graph
Analysis
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.”
DFS, BFS均可以解此题,有趣的是Union Find的解法。// TODO: Add DFS, BFS
This problem can be converted to finding a cycle in a graph. It can be solved by using DFS (Recursion) or BFS (Queue).
Union Find 思路
初始化Union Find的father map,让每一个节点的初始parent指向自己(自己跟自己是一个Group);在循环读取edge list时,查找两个节点的parent,如果相同,说明形成了环(Cycle),那么这便不符合树(Tree)的定义,反之,如果不相同,则将其中一个节点设为另一个的parent,继续循环。
此外还有需要注意的是对于vertex和edge的validation,|E| = |V| - 1,也就是要验证 edges.length == n - 1,如果该条件不满足,则Graph一定不是valid tree。
DFS / BFS
把输入的edge list转化为adjacency list,便于基于vertex的搜索。
BFS
在于每次遍历邻接表时,对于node的neighbor,放入BFS的queue中之后,就把node本身从neighbor的邻接表中移除。
或者,只在neighbor没有被遍历过时才放入queue中:
这样,在遍历出队列时,如果遇到元素被二次访问就说明有cycle。
最后遍历visited[],确认每一个元素都被遍历到,才是valid tree(没有落单的节点)
DFS
DFS 类似,只是在recursive放入parent和当前节点curr时,选择curr != parent才进行下一层hasCycle的递归,这样如果出现二次访问,就说明了有cycle。
Solution
Union Find Solution
Simplified Union Find (0ms 100%)
Union Find - with path compression and weighted (1ms, 74.31%)
DFS Solution
DFS - another one
BFS Solution
BFS - Another One
Reference
Last updated
Was this helpful?