DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

DFS TRAVERSAL

In a binary tree, there are three types of depth-first traversals:

Pre-order
Post-order
In-order

DFS (Depth-First Search) explores depth-wise. If there is no path forward, it backtracks and checks for other possible paths

.
DFS follows pre-order traversal in trees. We start from the root node, move to the left subtree, and visit all its nodes before moving to the right subtree. . In a tree, cycles do not exist, but in a graph, they can exist.

**Time Complexity:
**O(Vertex + Edge) = O(V + E)

**
Concepts Involved:**
DFS is based on recursion and backtracking.
We ensure that we do not visit the same node more than once.
To store the graph, we use an adjacency list.
DFS is used in applications like finding connected components, detecting cycles, and pathfinding.

BFS vs DFS:
DFS explores depth-wise, whereas
BFS (Breadth-First Search) explores level-wise..

Implementation

#include <bits/stdc++.h>
using namespace std;
vector<int> adj_list[1005];
bool vis[1005];

void dfs(int src)
{

    cout << src << " ";
    vis[src] = true;
    for (int child : adj_list[src])
    {
        if (vis[child] == false)
            dfs(child);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n, e;
    cin >> n >> e;
    while (e--)
    {
        int a,b ;
        cin >> a >> b ;
        adj_list[a].push_back(b);
        adj_list[b].push_back(a);
    }
    dfs(0) ;
}
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE