Skip to main content

What is breadth-first tree traversal (BFS)?

Breadth-first traversal (BFS, Breadth-First Search) is a way of traversing a tree in which nodes are visited level by level, starting from the root and moving left to right at each level.


How it works

  1. Start at the root.
  2. Visit all nodes at the first level (the root's children).
  3. Then visit all nodes at the second level, then the third, and so on.
  4. A queue (FIFO) is used to keep track of the traversal order.

Step-by-step example

javascript
A / \ B C / \ \ D E F

Traversal order: A → B → C → D → E → F

The queue during traversal:

javascript
1. [A] 2. [B, C] 3. [C, D, E] 4. [D, E, F] 5. [E, F] 6. [F] 7. []

Features of BFS

  • Based on a queue.
  • Good for finding the shortest path in unweighted graphs.
  • Visits nodes layer by layer, not by depth.

Summary

BFS is a traversal that goes level by level from top to bottom, using a queue to remember the order of nodes, so that nodes close to the root are processed first, and deeper ones later.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.