Skip to content

Instantly share code, notes, and snippets.

@Jenjen1324
Last active August 5, 2020 07:57
Show Gist options
  • Save Jenjen1324/e77535cd654d6a4140de76d7b4b5937b to your computer and use it in GitHub Desktop.
Save Jenjen1324/e77535cd654d6a4140de76d7b4b5937b to your computer and use it in GitHub Desktop.
/**
* Finds a node from a tree-like datastructure
*
* Could be easily implemented as DFS by switching `stack.shift()` to `stack.pop()`
*
* @param rootNode Root node of the tree-like datastructure
* @param obtainChildren Return children of a given node
* @param test Return true if the given node is the searched for one
* @returns {?T} the given node if found or null
*/
function FindNodeBFS<T>(
rootNode: T,
obtainChildren: (node: T) => Array<T>,
test: (node: T) => Boolean): T {
const stack: Array<T> = []
stack.push(rootNode)
while(stack.length > 0) {
const node = stack.shift() // Using shift (queue-like) for BFS, alternatively use pop for DFS
if (test(node)) {
return node
}
obtainChildren(node).forEach(child => stack.push(child))
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment