Created
March 22, 2021 21:06
-
-
Save tjeastmond/f7c689cd9f7b4591148f544db379d4d7 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
/** | |
* 10 | |
* / \ | |
* 4 17 | |
* / \ / \ | |
* 1 9 12 18 | |
* / | |
* 22 | |
*/ | |
const graphList = [ | |
[10, 4, 17], | |
[4, 1, 9], | |
[17, 12, 18], | |
[1, 22], | |
[9], | |
[12], | |
[18], | |
[22], | |
]; | |
const graph = new Map(); | |
function addNodes(node, left = null, right = null) { | |
graph.set(node, { value: node, left, right }); | |
} | |
graphList.forEach(nodes => addNodes(...nodes)); | |
function BreadthFirstSearch(graph, root, value) { | |
const path = []; | |
const queue = [graph.get(root)]; | |
while (queue.length > 0) { | |
const currentNode = queue.shift(); | |
path.push(currentNode.value); | |
if (currentNode.value === value) { | |
return path; | |
} | |
if (currentNode.left) { | |
queue.push(graph.get(currentNode.left)); | |
} | |
if (currentNode.right) { | |
queue.push(graph.get(currentNode.right)); | |
} | |
} | |
console.log('Could not find the node'); | |
return []; | |
} | |
console.log('graph:', graph); | |
console.log(BreadthFirstSearch(graph, 10, 12)); | |
console.log(BreadthFirstSearch(graph, 17, 18)); | |
console.log(BreadthFirstSearch(graph, 10, 22)); | |
console.log(BreadthFirstSearch(graph, 10, 99)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output from the
console.logs()
: