Last active
January 29, 2020 22:41
-
-
Save 20k-ultra/55317db00dbf018f8c82f659f7d2f4a9 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
let nodes = [] // list of nodes | |
const ROOT //binary tree with getChildren function implemented | |
getNodes(ROOT.getChildren()) // start recursion with no level_index so default is used | |
function getNodes(level, level_index = 0) { | |
level.forEach(node => { // loop threw nodes in the level | |
if (Array.isArray(nodes[level_index])) { | |
nodes[level_index].push(node) // if node already in this level then add | |
} else { | |
nodes[level_index] = [node] // first node in this level so create array | |
} | |
// repeat with this nodes children and descend 1 level | |
getNodes(node.getChildren(), level_index + 1) | |
}); | |
} | |
nodes[2].join(",") // return list of values from nodes on the 3rd level with comma delimiter |
demo script using this algorithm can be found here
demo script implementing Breadth-first search algorithm can be seen here.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem with this algorithm is it is all or nothing. We cannot ask it to find nodes only up to level 2. It must traverse the whole tree to return the levels.
https://en.wikipedia.org/wiki/Breadth-first_search is the correct implementation which allows you to exit early once you've reached the level you want.
The algorithm unintentionally implemented is known as https://en.wikipedia.org/wiki/Depth-first_search.