How do I visualize a tree dfs traversal?

I kind of have the intuition of its traversal, but I feel like I wanna visualize it even better...I want to make myself sure of the thing that tree traversal will take each and every element and terminates. How do you visualize it? Sorry for the naivety, but have been trying and then thought to put it up here. Thanks in advance :)


Solution 1:

Suppose we have the next tree and, therefore, the algorithm Depth first search will be performed relatively of the every vertex:

enter image description here

I can offer the solution of your problem as a proof, performed in C++:

#include <iostream>
#include <vector>
using namespace std;
const int maximumSize=10;
vector<int> visited(maximumSize, 0);
vector<int> graph[maximumSize];
int vertices, edges;
void createGraph()
{
    cin>>vertices>>edges;
    int vertex0, vertex1;
    for(int edge=1; edge<=edges; ++edge)
    {
        cin>>vertex0>>vertex1;
        graph[vertex0].push_back(vertex1);
        graph[vertex1].push_back(vertex0);
    }
    return;
}
void dfs(int current, int previous)
{
    if(visited[current]==1)
    {
        return;
    }
    visited[current]=1;
    cout<<"Current vertex is <- "<<current<<", previous vertex is <- "<<previous<<endl;
    for(int next : graph[current])
    {
        if(next==previous)
        {
            continue;
        }
        dfs(next, current);
    }
    return;
}
void solve()
{
    createGraph();
    dfs(1, 0);
    return;
}
int main()
{
    solve();
    return 0;
}

Input:

6 5
1 2
2 3
2 4
1 6
6 5

Output:

Current vertex is <- 1, previous vertex is <- 0
Current vertex is <- 2, previous vertex is <- 1
Current vertex is <- 3, previous vertex is <- 2
Current vertex is <- 4, previous vertex is <- 2
Current vertex is <- 6, previous vertex is <- 1
Current vertex is <- 5, previous vertex is <- 6