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 TreeLevel-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
- Add the root node to a queue.
- While the queue is not empty, remove the front node and visit it.
- Add that node's left child to the queue, if it exists.
- Add that node's right child to the queue, if it exists.
- Repeat until the queue is empty.
Level-order Worked Example
Input: Tree: root(1), left(2), right(3)
- Queue: [1] → visit 1, add children → Queue: [2, 3]
- Visit 2 (no children) → Queue: [3]
- Visit 3 (no children) → Queue: []
Output: 1, 2, 3
Press ▶ Run to watch it step by step.
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: levelOrderBehind 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.