Last active
February 15, 2020 22:26
-
-
Save reergymerej/53be9726ae42056e6f6a32632a975242 to your computer and use it in GitHub Desktop.
simple bfs/dfs comparison
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
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