Last active
August 5, 2020 07:57
-
-
Save Jenjen1324/e77535cd654d6a4140de76d7b4b5937b to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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