Let's assume that we have the following tree:
terminal0 / \ / \ 1 2 / \ / \ 3 4 / \ / \ 5 6 /|\ / | \ 7 8 9
Let's define a node:
javascriptlet node = (number, childs) => ({ number: number, childs: childs });
A tree will be an array of nodes:
javascriptlet tree = [node(0, [1, 2]), node(1, []), ... , node(6, [7, 8, 9]), ..., node(9, [])];
We will define an array to know visited nodes:
javascriptlet visited = Array(tree.length).fill(false);
Depth-first search algorithm (DFS) explores deeper nodes first before going backwards.
Let's define the algorithm:
javascriptconst 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:
javascriptdfs(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.