File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ time: O(n + m), where n is the number of nodes and m is the number of edges in the graph.
3
+ space: O(n + m)
4
+ */
5
+ class Solution {
6
+
7
+ public boolean validTree (int n , int [][] edges ) {
8
+
9
+ if (edges .length != n - 1 ) {
10
+ return false ;
11
+ }
12
+
13
+ List <List <Integer >> adjList = new ArrayList <>();
14
+ for (int i = 0 ; i < n ; i ++) {
15
+ adjList .add (new ArrayList <>());
16
+ }
17
+ for (int [] edge : edges ) {
18
+ adjList .get (edge [0 ])
19
+ .add (edge [1 ]);
20
+ adjList .get (edge [1 ])
21
+ .add (edge [0 ]);
22
+ }
23
+
24
+ Stack <Integer > stack = new Stack <>();
25
+ Set <Integer > visited = new HashSet <>();
26
+ stack .push (0 );
27
+ visited .add (0 );
28
+
29
+ while (!stack .isEmpty ()) {
30
+ int curr = stack .pop ();
31
+ for (int adj : adjList .get (curr )) {
32
+ if (visited .contains (adj )) {
33
+ continue ;
34
+ }
35
+ visited .add (adj );
36
+ stack .push (adj );
37
+ }
38
+ }
39
+
40
+ return visited .size () == n ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments