Created
April 7, 2022 18:55
-
-
Save JoeCortopassi/2a894a074be00a4f536e17b843d69fd2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor (val) { | |
this.value = val; | |
this.children = []; | |
} | |
} | |
function depthFirstSearch(seek, node) { | |
if (seek === node.value) return node; | |
for (let i=0; i<node.children.length; i++) { | |
const child = node.children[i]; | |
const result = depthFirstSearch(seek, child); | |
if (result !== -1) { | |
return [node].concat(result); | |
} | |
} | |
return -1; | |
} | |
const tree = new Node(5); | |
tree.children.push(new Node(3)); | |
tree.children.push(new Node(4)); | |
tree.children.push(new Node(6)); | |
tree.children[0].children.push(new Node(1)); | |
tree.children[0].children.push(new Node(2)); | |
tree.children[2].children.push(new Node(7)); | |
tree.children[2].children.push(new Node(8)); | |
tree.children[2].children.push(new Node(9)); | |
console.log("Depth First Search"); | |
console.log(1, depthFirstSearch(1, tree).map(obj => obj.value)); | |
console.log(9, depthFirstSearch(9, tree).map(obj => obj.value)); | |
console.log(12, depthFirstSearch(12, tree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment