Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created January 12, 2014 18:01
Show Gist options
  • Save jack-wong-build/8388169 to your computer and use it in GitHub Desktop.
Save jack-wong-build/8388169 to your computer and use it in GitHub Desktop.
Breath first search implementation with a queue.
var breathFirstSearch = function(node){
var queue = [];
// visit root
console.log("Node key, value", node.key, node.value);
root.visit=true;
queue.push(root);
while(queue.length !== 0){
currentNode = queue.pop();
for(var i = 0; i < currentNode.next.length; i++){
// visit root
if (currentNode.next[i].visit === false){
console.log("Node key, value", currentNode.next[i].key, currentNode.next[i].value);
currentNode.next[i].visit = true;
queue.push(currentNode.next[i]);
}
}
}
}
var makeNode = function(key, value){
var obj = {"key": key,
"value": value,
"next": [],
visit: false};
return obj;
}
// var root = makeNode("1", "apple");
// var node1 = makeNode("2", "orange");
// var node2 = makeNode("3", "kiwi");
// root.next.push(node1);
// root.next.push(node2);
// var node1 = makeNode("4", "banana");
// var node2 = makeNode("5", "blueberry");
// root.next[0].next.push(node1);
// root.next[0].next.push(node2);
// var node1 = makeNode("6", "grape");
// var node2 = makeNode("8", "pineapple");
// root.next[1].next.push(node1);
// root.next[1].next.push(node2);
// breathFirstSearch(root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment