Created
May 29, 2017 05:28
-
-
Save vaidehijoshi/27f9fa6b6b68f70360019805b5ca3692 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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