Skip to content

Commit 9784830

Browse files
committed
Graph Valid Tree Solution
1 parent 7d6ff24 commit 9784830

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

graph-valid-tree/PDKhan.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
};

0 commit comments

Comments
 (0)