graph-valid-tree 1.0.0
Graph Valid Tree
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7public:
8 bool validTree(int n, vector<vector<int>>& edges)
9 {
10 if ((int)edges.size() != n - 1)
11 return false;
12
13 // building adjacency list
14 unordered_map<int, list<int>> adj;
15 for (const auto& edge: edges)
16 {
17 adj[edge[0]].push_back(edge[1]);
18 adj[edge[1]].push_back(edge[0]);
19 }
20
21 stack<pair<int, int>> s; // stack to store (node, parent)
22 s.push({0, -1}); // start DFS from node 0 with parent -1
23 vector<bool> visited(n, false); // vector to track visited nodes
24 int processed = 0;
25
26 while (!s.empty())
27 {
28 auto [node, parent] = s.top();
29 s.pop();
30
31 if (visited[node])
32 return false;
33
34 visited[node] = true;
35 processed++;
36
37 for (int neighbor: adj[node])
38 {
39 if (!visited[neighbor])
40 s.push({neighbor, node});
41 else if (neighbor != parent)
42 return false; // cycle detected
43 }
44 }
45
46 return processed == n; // check if all nodes are visited
47 }
48};
49
50int main()
51{
52 vector<vector<int>> edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}};
53 cout << "output: " << Solution().validTree(5, edges) << '\n';
54 return 0;
55}
bool validTree(int n, vector< vector< int > > &edges)
Definition main.cpp:8
int main()
Definition main.cpp:50