Back

Binary Tree BFS (Breadth-First Search)

Tree Selection

Playback Controls

Frame 1 of 1
Loading tree visualization...
Time: O(n)
Space: O(w)

Algorithm Progress

Tree Nodes: 7
Tree Edges: 6
Search Target: None (Full Traversal)

Reference implementation of BFS (Breadth-First Search). Select a language tab to view and copy the code.

from collections import deque

def bfs(adj: list[list[int]], start: int) -> list[int]:
    visited = [False] * len(adj)
    order   = []
    queue   = deque([start])
    visited[start] = True

    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in adj[node]:
            if not visited[neighbor]:
                visited[neighbor] = True
                queue.append(neighbor)
    return order

Python — Code Walkthrough

  1. collections.deque for O(1) popleft

    from collections import deque; queue = deque([start])

    A Python list used as a queue has O(n) pop(0). collections.deque provides O(1) popleft and append, making it the standard choice for BFS in Python.

  2. Initialise with start node already marked

    queue = deque([start]); visited[start] = True

    Marking the start node before the loop follows the same "mark when enqueued" pattern, ensuring correctness even if the graph has a self-loop at the start node.

  3. node = queue.popleft()

    node = queue.popleft()

    popleft removes from the left (front) of the deque — the FIFO behavior needed for BFS. queue.pop() would give LIFO (DFS) behavior.

  4. Returns traversal order

    return order

    Rather than side-effecting with print, the function collects nodes into a list and returns it — more Pythonic and easier to test.