for days I am now trying to solve the following problem. A recursive function is suppose to iterate through a dictionary that is basically a representation of a tree.
The input looks like this:
var connections = {1:[2, 3, 4], 2:[5, 6, 7], 3:[8], 4:[9, 10]}
and the corresponding tree that it represents looks like this:

The intermediate goal is to print out the numbers in a depht first search manner, namely:

My solution for this problem is:
function dfs(connections, parent) {
console.log(parent);
if (!(parent in connections)) {
return;
}
for (i = 0; i < connections[parent].length; i++) {
dfs(connections, connections[parent][i]);
}
return;
}
However, calling the function
dfs(connections, 1)
leads to the following result:
1
2
5
6
7
That means it is not returning to the previous function and continuing the for-loop. If you have any idea whatsoever, I would be very grateful.
Cheers
for (let i = 0; i < connections[parent].length; i++)Otherwise you are declaring a global and it's getting clobbered on recursion.i.