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
.
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
.
1 public class Solution { 2 // what is graph valid tree? 1: all the nodes are connected 2: no cycle 3 public bool ValidTree(int n, int[,] edges) { 4 var al = new Dictionary<int, HashSet<int>>(); 5 6 for (int i = 0; i < edges.GetLength(0); i++) 7 { 8 var v1 = edges[i, 0]; 9 var v2 = edges[i, 1]; 10 11 if (!al.ContainsKey(v1)) 12 { 13 al[v1] = new HashSet<int>(); 14 } 15 16 al[v1].Add(v2); 17 18 if (!al.ContainsKey(v2)) 19 { 20 al[v2] = new HashSet<int>(); 21 } 22 23 al[v2].Add(v1); 24 } 25 26 // make sure we can traverse all the nodes from root and there is no cycle 27 var queue = new Queue<int>(); 28 queue.Enqueue(0); 29 var visited = new bool[n]; 30 31 while (queue.Count > 0) 32 { 33 var node = queue.Dequeue(); 34 35 if (visited[node]) 36 { 37 return false; 38 } 39 40 visited[node] = true; 41 42 if (al.ContainsKey(node) && al[node] != null) 43 { 44 foreach (var nn in al[node]) 45 { 46 // as we already traverse node -> nn, we need to remove the edge from nn -> node as traversing tree is one way only 47 al[nn].Remove(node); 48 queue.Enqueue(nn); 49 } 50 } 51 } 52 53 for (int i = 0; i < n; i++) 54 { 55 if (!visited[i]) return false; 56 } 57 58 return true; 59 } 60 }