BFS/DFS Made Simple
Breadth-First Search (BFS)
- Create a queue, add the root node.
- While the queue has nodes, dequeue one.
- Visit the node.
- Add its children to the queue.
- Repeat.
Depth-First Search (DFS)
- Create a stack, add the root node.
- While the stack has nodes, pop one.
- Visit the node.
- Add its children to the stack.
- Repeat until the stack is empty.
Simplify
The real difference is only how we select the next node. Here’s a generic implementation common to both.
const search = nextNode => (root, visit) => {
let list = [root]
while (list.length) {
const node = nextNode(list)
visit(node)
list = list.concat(node.children)
}
}
That’s it. If you can remember this, you’ve got them both down. Of course, there are complexities like cycles in graphs and inorder/postorder/preorder, but this is the basic concept.