So I am doing algorithm problems on AlgoExpert, and I came across a recursive DFS algorithm. Originally I tried solving it in JavaScript but was having issues. When I watched the code walk-through I saw that the way it was solved is super easy.
Here is the Python solution:
def depthFirstSearch(self, array):
array.append(self.name);
for child in self.children:
child.depthFirstSearch(array);
return array
My question is, how would you achieve the same thing in JavaScript? I tried doing:
function depthFirstSearch(array) {
array.push(this.name);
for(let i=0; i < array.length; i++) {
depthFirstSearch(array[i]);
};
return array;
}
I keep getting an error:
depthFirstSearch is not defined
I'm confused about why I'm getting the error in JavaScript, when I'm trying to recursively call the function within itself?
Here is the whole code snippet:
class Node {
constructor(name) {
this.name = name;
this.children = [];
}
addChild(name) {
this.children.push(new Node(name));
return this;
}
depthFirstSearch(array) {
/*
* Step 1: Add the root node to the array
* this.name is the root at the start
* Step 2: Check that the left child node isn't null
* Step 3: If the left child node isn't null, Add the left child node to the array
* Step 4: If the left child node is null check the right child node
* Step 5: If the right child node isn't null, add the right child node to the array
* Step 6: Repeat steps 1-5 until there are no nodes left to check
*/
array.push(this.name);
const children = this.children;
for(let i=0; i < array.length; i++) {
depthFirstSearch(array[i]);
};
return array;
}
}
this.depthFirstSearch(array[i])? Because your function is defined in a class, it isn't accessible by just callingdepthFirstSearch.this.depthFirstSearch(array[i])and it said that array was undefined.