Last active
February 26, 2020 21:45
-
-
Save Giagnus64/3b903b7feb8a9d6587f8e4b3bebb2281 to your computer and use it in GitHub Desktop.
Breadth First Search for Trees
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
traverseBFS() { | |
//if there is no root, return false | |
if (!this.root) { | |
return false; | |
} | |
//start a new Queue | |
const queue = new Queue(); | |
//keep a tally of all values in the tree | |
const treeValues = []; | |
//add root to queue | |
queue.enqueue(this.root); | |
//while queue is not empty | |
while (queue.size !== 0) { | |
//get TreeNode Children | |
const nodeChildren = queue.first.value.children; | |
//if node has children, loop and add each to queue | |
if (nodeChildren.length !== 0) { | |
nodeChildren.forEach(child => queue.enqueue(child)); | |
} | |
//push the first item in the queue to the tree values | |
treeValues.push(queue.first.value); | |
//remove first node from queue | |
queue.dequeue(); | |
} | |
//return values, should be all TreeNodes | |
return treeValues; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment