Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Concept

Introduction

Level by level with a FIFO queue
step 1 / 17
binary tree
4
2
5
1
6
3
7
queue (FIFO)
front →
(empty)
← back
Concept
1bfs(root):
2 queue = [root]
3 while queue not empty:
4 node = queue.dequeue() // front
5 if node is leaf: continue
6 enqueue node.children // back
7 // visits nodes level by level
state
  • orderlevel by level

line 1Breadth-First Search explores a tree LEVEL BY LEVEL — all depth-1 nodes, then all depth-2, and so on. The engine is a QUEUE (first-in, first-out): you take a node from the FRONT, and add its children to the BACK. Contrast DFS, which used a stack and plunged deep first.