Search
⌘K
Get Premium
Breadth First Search
Breadth-First Search (BFS) is a level-by-level traversal algorithm for trees and graphs. Unlike DFS which dives deep into one path before backtracking, BFS explores all nodes at the current level before moving to the next level. This makes BFS the go-to algorithm when you need shortest paths or level-order processing.
bfs(root)
queue = [root]
while queue not empty
node = queue.pop()
visit(node)
queue.add(node.left)
queue.add(node.right)
Watch how BFS visits the tree level by level: first A, then B and C (level 2), then D, E, F, and G (level 3). The queue ensures nodes are processed in the order they were discovered, creating this breadth-first behavior. We will explore BFS in-depth in upcoming lessons.
This module teaches you how to solve coding interview questions using breadth-first search by focusing on questions that are best solved using BFS rather than Depth-First Search. It's divided into 2 sections:
Binary Trees
We start by learning how breadth-first search traverses the nodes in a binary tree, which will teach us the fundamentals of the algorithm. We then look at practice problems that are best solved using BFS.
Graphs
We then look at the two most common ways graphs are represented during the coding interview, and how to traverse both representations with BFS. Then we work through problems that give us practice with the different types of graph problems that are best solved using BFS.
Mark as read
Unlock Premium Coding Content
Reading Progress
On This Page
Your account is free and you can post anonymously if you choose.