Skip to content

Instantly share code, notes, and snippets.

@20k-ultra
Last active January 29, 2020 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 20k-ultra/55317db00dbf018f8c82f659f7d2f4a9 to your computer and use it in GitHub Desktop.
Save 20k-ultra/55317db00dbf018f8c82f659f7d2f4a9 to your computer and use it in GitHub Desktop.
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
@20k-ultra
Copy link
Author

20k-ultra commented Jan 29, 2020

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.

@20k-ultra
Copy link
Author

20k-ultra commented Jan 29, 2020

demo script using this algorithm can be found here

@20k-ultra
Copy link
Author

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