DFS algorithm in JavaScript

Let's assume that we have the following tree:

terminal
    
    0
   / \
  /   \
 1     2
      / \
     /   \
    3     4
   / \
  /   \
 5     6
      /|\
     / | \
    7  8  9
    

Let's define a node:

javascript
let node = (number, childs) => ({
    
    number: number,
    childs: childs

});

A tree will be an array of nodes:

javascript
let tree = [node(0, [1, 2]), node(1, []), ... , node(6, [7, 8, 9]), ..., node(9, [])];

We will define an array to know visited nodes:

javascript
let visited = Array(tree.length).fill(false);

Depth-first search algorithm (DFS) explores deeper nodes first before going backwards.

Let's define the algorithm:

javascript
const dfs = (tree, start, visited) => {
    
    // Printing current value
    console.log(start);
    
    // Setting this node as visited
    visited[start] = true;
    
    // Getting next node to visit
    let nextNode = tree[start].childs.shift();
    
    while(nextNode && !visited[nextNode]){
    
        // Visiting next node
        dfs(tree, nextNode, visited);
        
        // Finding next node
        nextNode = tree[start].childs.shift();
        
    }
    
}

Executing the algorithm:

javascript
dfs(tree, 0, visited);

// 0, 1, 2, 3, 5, 6, 7, 8, 9, 4

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.