Created
April 7, 2022 18:54
-
-
Save JoeCortopassi/2d0fe6b1e6479b5b3f8008acd7371e85 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 breadthFirstSearch (seek,node) { | |
if (seek === node.value) return node; | |
const queue = [node]; | |
const path = {}; | |
while (queue.length > 0) { | |
const queuedNode = queue.shift(); | |
if (seek === queuedNode.value) { | |
let currentNode = queuedNode; | |
const pathToRoot = []; | |
while (currentNode) { | |
pathToRoot.push(currentNode); | |
currentNode = path[currentNode.value]; | |
} | |
return pathToRoot; | |
} | |
for (let i=0; i<queuedNode.children.length; i++) { | |
const child = queuedNode.children[i]; | |
path[child.value] = queuedNode; | |
queue.push(child); | |
} | |
} | |
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("Breadth First Search"); | |
console.log(1, breadthFirstSearch(1, tree));//.map(obj => obj.value)); | |
console.log(9, breadthFirstSearch(9, tree));//.map(obj => obj.value)); | |
console.log(12, breadthFirstSearch(12, tree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment