Skip to content

Instantly share code, notes, and snippets.

@vaidehijoshi
Created May 29, 2017 05:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaidehijoshi/27f9fa6b6b68f70360019805b5ca3692 to your computer and use it in GitHub Desktop.
Save vaidehijoshi/27f9fa6b6b68f70360019805b5ca3692 to your computer and use it in GitHub Desktop.
function levelOrderSearch(rootNode) {
// Check that a root node exists.
if (rootNode === null) {
return;
}
// Create our queue and push our root node into it.
var queue = [];
queue.push(rootNode);
// Continue searching through as queue as long as it's not empty.
while (queue.length > 0) {
// Create a reference to currentNode, at the top of the queue.
var currentNode = queue[0];
// If currentNode has a left child node, add it to the queue.
if (currentNode.left !== null) {
queue.push(currentNode.left)
}
// If currentNode has a right child node, add it to the queue.
if (currentNode.right !== null) {
queue.push(currentNode.right)
}
// Remove the currentNode from the queue.
queue.shift()
}
// Continue looping through the queue until it's empty!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment