Generating Binary Numbers Using Queues in Python

Hey folks! 👋 Today I dove into an interesting problem involving queues and binary numbers — and I want to share what I learned in a simple way.
What Are Binary Numbers?
Binary numbers are just numbers made up of only 0s and 1s — the base language of computers. For example:
Decimal 1 = Binary
1
Decimal 2 = Binary
10
Decimal 3 = Binary
11
Decimal 4 = Binary
100
The Challenge
How do you generate the first n binary numbers in order, without converting each decimal number one by one?
The answer: use a queue and build them step-by-step like a binary tree!
How Does It Work?
We start with '1'
in a queue. Each time we:
Pop the front binary number from the queue.
Add it to our result list.
Append two new numbers to the queue:
The current number +
'0'
The current number +
'1'
This way, every number generates two “children” by adding a 0 or 1, like this binary tree:
1
/ \
10 11
/ \ / \
100 101 110 111
Here’s the Code!
from collections import deque
def generate_binary_numbers(n):
queue = deque(['1'])
result = []
for _ in range(n):
front = queue.popleft()
result.append(front)
queue.append(front + '0')
queue.append(front + '1')
return result
n = int(input("Enter the number of binary numbers to generate: "))
print(generate_binary_numbers(n))
Why Use This Approach?
No need to convert from decimal — we directly build the binary numbers as strings.
It’s a clean, logical way to generate sequences using queues and trees.
Helps you understand breadth-first traversal and the power of queues.
Great for coding interviews and algorithm practice!
Real-World Applications
Generating all bit sequences of length
n
for network protocols.Building binary decision trees.
Encoding problems and compression algorithms.
Any situation where you need to systematically generate combinations.
Final Thoughts
Queues aren’t just about waiting in line — they’re a powerful data structure to generate sequences like binary numbers efficiently and clearly. If you’re new to queues, this is a great exercise to deepen your understanding.
Subscribe to my newsletter
Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
