Breadth-First Search (BFS)

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a ‘search key’) and explores the neighbor nodes first, before moving to the next level neighbors.

Algorithm Visualization

Pseudocode

  1. BFS(root)
  2. Pre: root is the node of the BST
  3. Post: the nodes in the BST have been visited in breadth first order
  4. q queue
  5. while root = ø
  6. yield root.value
  7. if root.left = ø
  8. q.enqueue(root.left)
  9. end if
  10. if root.right = ø
  11. q.enqueue(root.right)
  12. end if
  13. if !q.isEmpty()
  14. root q.dequeue()
  15. else
  16. root ø
  17. end if
  18. end while
  19. end BFS

References