Breadth-First Search (BFS) for Trees
Breadth-First Search (BFS) is an algorithm for traversing or searching tree or graph data structures. It explores the neighbor nodes first, before moving to the next level neighbors.
Interactive BFS Traversal Visualization
The visualization below demonstrates the BFS traversal process on a sample tree. You can see how the algorithm explores the tree level by level.
BFS Traversal (Tree)
Step 1 of 0
Action
Ready to start
Current Node
None
Queue
[]
Traversal Order
[]
Current Node
Visited
In Queue
Unvisited
Breadth-First Search (BFS) Algorithm
Breadth-First Search (BFS) is a tree and graph traversal algorithm that explores neighbor nodes first, before moving to the next level neighbors. It's also known as a level-order traversal, as it visits nodes level by level.
Algorithm Steps
- Create a queue and add the root node to it.
- While the queue is not empty, do the following:
- Dequeue a node and process it (e.g., add its value to a list).
- Enqueue its left child, if it exists.
- Enqueue its right child, if it exists.
- Repeat until the queue is empty.
BFS (Level-Order) Traversal