Skip to content

Instantly share code, notes, and snippets.

@reergymerej
Last active February 15, 2020 22:26
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 reergymerej/53be9726ae42056e6f6a32632a975242 to your computer and use it in GitHub Desktop.
Save reergymerej/53be9726ae42056e6f6a32632a975242 to your computer and use it in GitHub Desktop.
simple bfs/dfs comparison
const search = nextNode => (root, visit) => {
let list = [root]
while (list.length) {
const node = nextNode(list)
visit(node)
list = list.concat(node.children)
}
}
const bfs = search(list => list.shift())
const dfs = search(list => list.pop())
const tree = {
data: 's',
children: [
{ data: 1,
children: [
{ data: 3, children: [] },
{ data: 4, children: [] },
],
},
{ data: 2,
children: [
{ data: 5, children: [] },
],
},
],
}
const visit = (node) => console.log(node.data)
bfs(tree, visit)
dfs(tree, visit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment