graph-valid-tree 1.0.0
Graph Valid Tree
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

bool validTree (int n, vector< vector< int > > &edges)
 

Detailed Description

Definition at line 5 of file main.cpp.

Member Function Documentation

◆ validTree()

bool Solution::validTree ( int  n,
vector< vector< int > > &  edges 
)
inline

Definition at line 8 of file main.cpp.

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 }

Referenced by main().


The documentation for this class was generated from the following file: