forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0261-graph-valid-tree.cpp
49 lines (44 loc) · 1.37 KB
/
0261-graph-valid-tree.cpp
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
47
48
49
/*
Graph of nodes, list of edges, determine if edges make valid tree
Ex. n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] -> true
(1) For graph to be a valid tree, must have exactly n - 1 edges
(2) If graph fully connected & has n - 1 edges, can't contain cycle
Time: O(n)
Space: O(n)
*/
class Solution {
public:
bool validTree(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
for (int i = 0; i < edges.size(); i++) {
vector<int> edge = edges[i];
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
vector<bool> visited(n);
if (hasCycle(adj, visited, -1, 0)) {
return false;
}
for (int i = 0; i < visited.size(); i++) {
if (!visited[i]) {
return false;
}
}
return true;
}
private:
bool hasCycle(vector<vector<int>>& adj, vector<bool>& visited, int parent, int child) {
if (visited[child]) {
return true;
}
visited[child] = true;
// checking for cycles and connectedness
for (int i = 0; i < adj[child].size(); i++) {
int curr = adj[child][i];
if (curr != parent && hasCycle(adj, visited, child, curr)) {
return true;
}
}
return false;
}
};