Data Structures · Visualization

Binary Tree: Level-order

Binary Tree

Level-order traversal visits nodes row by row, from top to bottom and left to right within each row — this is simply a breadth-first search (BFS) applied to a tree. Time: O(n). Space: O(n) for the queue in the worst case (a wide tree).

Big-O: Traversals visit every node exactly once: O(n).

Binary Tree: Level-order

Binary Tree

Level-order traversal visits nodes row by row, from top to bottom and left to right within each row — this is simply a breadth-first search (BFS) applied to a tree. It uses a queue: nodes are visited in the order they are added, and each visited node's children are added to the back of the queue.

How Level-order Works

  1. Add the root node to a queue.
  2. While the queue is not empty, remove the front node and visit it.
  3. Add that node's left child to the queue, if it exists.
  4. Add that node's right child to the queue, if it exists.
  5. Repeat until the queue is empty.

Level-order Worked Example

Input: Tree: root(1), left(2), right(3)

  1. Queue: [1] → visit 1, add children → Queue: [2, 3]
  2. Visit 2 (no children) → Queue: [3]
  3. Visit 3 (no children) → Queue: []

Output: 1, 2, 3

Binary Tree: Introduction
A hierarchy of nodes where each node has at most two children — usually called "left" and "right".
45
20
10
30
40
65
50
60
70
80
Active Result
Binary Tree: Introduction
Press ▶ Run to watch it step by step.
Python · Binary Trees in Code
from collections import deque

def level_order(root):
    if not root:
        return
    q = deque([root])
    while q:
        n = q.popleft()       # FIFO: level by level
        print(n.val, end=" ")
        if n.left:
            q.append(n.left)
        if n.right:
            q.append(n.right)
# example: levelOrder
Input: Tree: root(1), left(2), right(3)

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Level-order Time & Space Complexity

TimeO(n)
SpaceO(n) for the queue in the worst case (a wide tree)

When to Use Level-order

  • Printing a tree row by row for visualization
  • Finding the shortest path in an unweighted tree-like structure
  • Serializing a tree in a format that mirrors its shape

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.