File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ bool dfs (int curr, int parent, vector<vector<int >>& graph, vector<int >& visited){
4
+ if (visited[curr])
5
+ return false ;
6
+
7
+ visited[curr] = 1 ;
8
+
9
+ for (int i = 0 ; i < graph[curr].size (); i++){
10
+ if (graph[curr][i] == parent)
11
+ continue ;
12
+
13
+ if (dfs (graph[curr][i], curr, graph, visited) == false )
14
+ return false ;
15
+ }
16
+
17
+ return true ;
18
+ }
19
+
20
+ bool validTree (int n, vector<vector<int >> &edges) {
21
+ // write your code here
22
+ if (edges.size () != n - 1 )
23
+ return false ;
24
+
25
+ vector<vector<int >> graph (n);
26
+ vector<int > visited (n, 0 );
27
+
28
+ for (int i = 0 ; i < edges.size (); i++){
29
+ int first = edges[i][0 ];
30
+ int second = edges[i][1 ];
31
+
32
+ graph[first].push_back (second);
33
+ graph[second].push_back (first);
34
+ }
35
+
36
+ if (dfs (0 , -1 , graph, visited) == false )
37
+ return false ;
38
+
39
+ for (int i = 0 ; i < n; i++){
40
+ if (visited[i] == 0 )
41
+ return false ;
42
+ }
43
+
44
+ return true ;
45
+ }
46
+ };
You can’t perform that action at this time.
0 commit comments