Breadth-first search (BFS)
Walking a tree or graph level by level: first the ones closest to the start, then the next ones. It uses a queue.
Example
With root 1, children 2 and 3, and grandchildren 4, 5, 6 and 7, BFS visits 1, 2, 3, 4, 5, 6, 7.
Test yourself: Breadth-first search (BFS)
Walking a tree
What structure does level-order traversal use?
1 is dequeued and 2 and 3 enqueued; 2 is dequeued and 4 and 5 enqueued, landing behind 3. That way level 2 comes out whole before level 3.
Walking a tree
You're looking for the node with value 7 that's closest to the root. Which traversal fits?
BFS checks all of level 2 before level 3: the first 7 it finds is the shallowest. DFS might first find one on level 10.
Trees in an array
In a tree stored in an array, reading the array left to right gives the ___ traversal.
[1, 2, 3, 4, 5] is already in level order: 1, then 2 and 3, then 4 and 5. That's 5 reads, no queue.
0/3
â–¶ Play