forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDKhan.cpp
More file actions
46 lines (35 loc) · 1.31 KB
/
PDKhan.cpp
File metadata and controls
46 lines (35 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public:
bool dfs(int curr, int parent, vector<vector<int>>& graph, vector<int>& visited){
if(visited[curr])
return false;
visited[curr] = 1;
for(int i = 0; i < graph[curr].size(); i++){
if(graph[curr][i] == parent)
continue;
if(dfs(graph[curr][i], curr, graph, visited) == false)
return false;
}
return true;
}
bool validTree(int n, vector<vector<int>> &edges) {
// write your code here
if(edges.size() != n - 1)
return false;
vector<vector<int>> graph (n);
vector<int> visited (n, 0);
for(int i = 0; i < edges.size(); i++){
int first = edges[i][0];
int second = edges[i][1];
graph[first].push_back(second);
graph[second].push_back(first);
}
if(dfs(0, -1, graph, visited) == false)
return false;
for(int i = 0; i < n; i++){
if(visited[i] == 0)
return false;
}
return true;
}
};