Visit nodes level by level using a queue. On trees, this gives you level-order traversal. On graphs, it gives you shortest paths. Same algorithm, one extra line.
What Is It?
Breadth-first search explores nodes in order of their distance from the start. You use a queue: dequeue a node, process it, enqueue its children (or neighbors). The queue ensures you process everything at distance d before anything at distance d+1.
On a binary tree, BFS is called level-order traversal. Start with the root in the queue, dequeue a node, enqueue its left and right children. You naturally visit nodes layer by layer. No visited check needed — trees have no cycles.
On a graph, the same idea applies, but you add a dist array (or seen set) to avoid revisiting nodes. The first time you reach a node is the shortest path to it (in terms of edge count). This is the fundamental property that makes BFS powerful for graphs.