My Docs
BlogGithubLinkedin
Data Structures & Algorithms
Data Structures & Algorithms
  • Data Structures & Algorithms
  • trees
    • 🌳Trees
    • Page 1
      • Breadth-First Search (BFS)
  • 🕸️Graph
    • Graphs
    • ⛓️Linked List
    • Binary Search
    • Linear Search
Powered by GitBook
On this page
  • Pseudocode
  • References

Was this helpful?

Edit on GitHub
  1. trees
  2. Page 1

Breadth-First Search (BFS)

PreviousPage 1NextGraphs

Last updated 3 years ago

Was this helpful?

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

BFS(root)
  Pre: root is the node of the BST
  Post: the nodes in the BST have been visited in breadth first order
  q ← queue
  while root = ø
    yield root.value
    if root.left = ø
      q.enqueue(root.left)
    end if
    if root.right = ø
      q.enqueue(root.right)
    end if
    if !q.isEmpty()
      root ← q.dequeue()
    else
      root ← ø
    end if
  end while
end BFS

References

Wikipedia
Tree Traversals (Inorder, Preorder and Postorder)
BFS vs DFS