# Program to print the DFS traversal step-wise using C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to print the steps of the traversal using Depth First Search in a given binary tree.

This would include every step that occurs in the depth-first search including the backtracking procedure as well.

During DFS, we will be traversing each node and simultaneously storing the parent node and the edge used. During the traversal, if the adjacent edge has been visited, then the exact node can be printed as a step in the depth-first search.

## Example

#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
//printing the steps in DFS traversal
void dfs_steps(int u, int node, bool visited[],
vector<pair<int, int< > path_used, int parent, int it){
int c = 0;
for (int i = 0; i < node; i++)
if (visited[i])
c++;
if (c == node)
return;
//marking the node as visited
visited[u] = true;
path_used.push_back({ parent, u });
cout << u << " ";
if (!visited[x])
dfs_steps(x, node, visited, path_used, u, it + 1);
}
for (auto y : path_used)
if (y.second == u)
dfs_steps(y.first, node, visited,
path_used, u, it + 1);
}
void dfs(int node){
bool visited[node];
vector<pair<int, int> > path_used;
for (int i = 0; i < node; i++)
visited[i] = false;
dfs_steps(0, node, visited, path_used, -1, 0);
}
}
int main(){
int node = 11, edge = 13;
}
0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10