-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
55 lines (45 loc) · 1.35 KB
/
main.cpp
File metadata and controls
55 lines (45 loc) · 1.35 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
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool validTree(int n, vector<vector<int>>& edges)
{
if ((int)edges.size() != n - 1)
return false;
// building adjacency list
unordered_map<int, list<int>> adj;
for (const auto& edge: edges)
{
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
stack<pair<int, int>> s; // stack to store (node, parent)
s.push({0, -1}); // start DFS from node 0 with parent -1
vector<bool> visited(n, false); // vector to track visited nodes
int processed = 0;
while (!s.empty())
{
auto [node, parent] = s.top();
s.pop();
if (visited[node])
return false;
visited[node] = true;
processed++;
for (int neighbor: adj[node])
{
if (!visited[neighbor])
s.push({neighbor, node});
else if (neighbor != parent)
return false; // cycle detected
}
}
return processed == n; // check if all nodes are visited
}
};
int main()
{
vector<vector<int>> edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}};
cout << "output: " << Solution().validTree(5, edges) << '\n';
return 0;
}