@@ -22,7 +22,7 @@ class Graph {
2222 }
2323 }
2424
25- // Function to perform BFS traversal
25+ // Iterative BFS traversal
2626 void bfs (int startNode) {
2727 vector<bool > visited (adjacencyList.size (), false ); // Visited array
2828 queue<int > q; // Queue for BFS
@@ -31,7 +31,7 @@ class Graph {
3131 visited[startNode] = true ;
3232 q.push (startNode);
3333
34- cout << " BFS Traversal: " ;
34+ cout << " BFS Traversal (Iterative) : " ;
3535
3636 while (!q.empty ()) {
3737 int currentNode = q.front ();
@@ -50,6 +50,46 @@ class Graph {
5050 }
5151 cout << endl;
5252 }
53+
54+ // Recursive BFS traversal
55+ void bfsRecursiveHelper (int startNode, vector<bool >& visited, queue<int >& q) {
56+ if (q.empty ()) {
57+ return ; // Base case: queue is empty, stop recursion
58+ }
59+
60+ int currentNode = q.front ();
61+ q.pop ();
62+
63+ // Process the current node (e.g., print it)
64+ cout << currentNode << " " ;
65+
66+ // Visit all unvisited neighbors
67+ for (int neighbor : adjacencyList[currentNode]) {
68+ if (!visited[neighbor]) {
69+ visited[neighbor] = true ;
70+ q.push (neighbor);
71+ }
72+ }
73+
74+ // Recursive call with the updated queue
75+ bfsRecursiveHelper (startNode, visited, q);
76+ }
77+
78+ void bfsRecursive (int startNode) {
79+ vector<bool > visited (adjacencyList.size (), false ); // Visited array
80+ queue<int > q; // Queue for BFS
81+
82+ // Start BFS from the startNode
83+ visited[startNode] = true ;
84+ q.push (startNode);
85+
86+ cout << " BFS Traversal (Recursive): " ;
87+
88+ // Start recursive BFS traversal
89+ bfsRecursiveHelper (startNode, visited, q);
90+
91+ cout << endl;
92+ }
5393};
5494
5595int main () {
@@ -65,8 +105,11 @@ int main() {
65105 g.addEdge (1 , 4 );
66106 g.addEdge (2 , 5 );
67107
68- // Perform BFS traversal starting from node 0
108+ // Perform BFS traversal starting from node 0 (Iterative)
69109 g.bfs (0 );
70110
111+ // Perform BFS traversal starting from node 0 (Recursive)
112+ g.bfsRecursive (0 );
113+
71114 return 0 ;
72115}
0 commit comments