Skip to content

Instantly share code, notes, and snippets.

@tjeastmond
Created March 22, 2021 21:06
Show Gist options
  • Save tjeastmond/f7c689cd9f7b4591148f544db379d4d7 to your computer and use it in GitHub Desktop.
Save tjeastmond/f7c689cd9f7b4591148f544db379d4d7 to your computer and use it in GitHub Desktop.
/**
* 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));
@tjeastmond
Copy link
Author

Output from the console.logs():

graph: Map(8) {
  10 => { value: 10, left: 4, right: 17 },
  4 => { value: 4, left: 1, right: 9 },
  17 => { value: 17, left: 12, right: 18 },
  1 => { value: 1, left: 22, right: null },
  9 => { value: 9, left: null, right: null },
  12 => { value: 12, left: null, right: null },
  18 => { value: 18, left: null, right: null },
  22 => { value: 22, left: null, right: null }
}
[ 10, 4, 17, 1, 9, 12 ]
[ 17, 12, 18 ]
[ 10,  4, 17,  1, 9, 12, 18, 22 ]
Could not find the node
[]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment