The depth_first_search()
method in the script above performs Preorder Traversal BFS. Let's create nodes for the example tree and test the working of depth_first_search()
method.
xxxxxxxxxx
79
dfs(1);
let graph;
​
const numOfNodes = 7;
let visited = new Array(numOfNodes);
​
const dfs = (node) => {
const stack = [];
stack.push(node);
​
while (stack.length) {
node = stack.pop();
​
if (!visited[node]) {
visited[node] = true;
​
console.log(`visiting ${node}`);
for (let j = 0; j < graph[node].length; j++) {
if (graph[node][j] === 1) {
stack.push(j);
}
}
}
}
};
​
// helper methods
​
const createGraph = (numOfNodes) => {
graph = new Array(numOfNodes);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment