xxxxxxxxxx
#include <bits/stdc++.h>
using namespace std;
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
void addEdge(int v, int w);
void DFS(int v);
void PrintGraph();
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
}
void Graph::PrintGraph()
{
for(auto &it:adj)
{
cout<<it.first<<" : ";
for(auto i=(it.second).begin();i!=(it.second).end();i++)
{
cout<<*i<<" -> ";
}
cout<<"NULL\n";
}
}
void Graph::DFS(int v)
{
visited[v]=true;
cout<<v<<" ";
for(auto i=adj[v].begin();i!=adj[v].end();i++)
{
if(!visited[*i])
{
DFS(*i);
}
}
}
int main()
{
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.PrintGraph();
g.DFS(2);
return 0;
}
xxxxxxxxxx
class Node {
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// depth first search tree traversal using recursive
//static implementation
const depthFirstTraversal = (root) => {
if (root === null) return [];
const leftValues = depthFirstTraversal(root.left); //[2 , 4 , 5 ]
const rightValues = depthFirstTraversal(root.right); // [3 , 6 , 7 ]
return [root.data, leftValues, rightValues];
};
const one = new Node(1);
const two = new Node(2);
const three = new Node(3);
const four = new Node(4);
const five = new Node(5);
const six = new Node(6);
const seven = new Node(7);
one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
// console.log(depthFirstTraversal(one)); // [1 ,2 , 4 , 5 ,3 , 6 ,7]
// depth first search tree traversal using while loop :
const depthFirstTraversal2 = (root) => {
if (root === null) return [];
const result = [];
const stack = [root];
while (stack.length > 0) {
const current = stack.pop();
result.push(current.data);
if (current.right) stack.push(current.right);
if (current.left) stack.push(current.left);
}
return result;
};
console.log(depthFirstTraversal2(one)); // [1 ,2 , 4 , 5 ,3 , 6 ,7]
xxxxxxxxxx
remember that you are putting the vertexes of your graph into a stack and that is what determines the order they are travelled
xxxxxxxxxx
const depthFirstTraversal = (root) => {
if (root === null) return [];
const result = [];
const stack = [root];
while (stack.length > 0) {
const current = stack.pop();
result.push(current.data);
if (current.right) stack.push(current.right);
if (current.left) stack.push(current.left);
}
return result;
};