Key differences between BFS and DFS are:
- BFS is vertex-based algorithm while DFS is an edge-based algorithm.
- Queue data structure is used in BFS. On the other hand, DFS uses stack or recursion.
- Memory space is efficiently utilised in DFS (
O(log n)
) while space utilisation in BFS (O(n)
) is not effective. - A depth-first search uses a stack, which contains nodes from root to the node being searched. So at most the radius of the graph (or depth of the tree).
- A breadth-first search uses a queue, which contains nodes at the front of the search. So at most all nodes at distance d.
- If you have a balanced (or mostly so) k-ary tree, it’s depth, i.e. radius, will be only
O(log n)
, while the lowest layer will containO(n)
nodes (n/2
for binary tree and even more for higher degrees). - BFS is optimal algorithm while DFS is not optimal. DFS may produce a much longer path than BFS.
- DFS constructs narrow and long trees. As against, BFS constructs wide and short tree.
- DFS is a genuinely recursive algorithm that uses stack for backtracking purposes, not for storing the vertex discovery “front” (as is the case in BFS).