← Back to DSA Animator
Serialize and Deserialize Binary Tree LC #297 Hard BFS · Serialize · Deserialize
Problem

Design an algorithm to serialize a binary tree to a string and deserialize that string back to the original tree. Use BFS (level-order) with "null" tokens for missing nodes.

Example 1
Input: root = [1,2,3,4,5]
Serialize: "1,2,3,4,5,null,null,null,null,null,null,"
Deserialize: rebuilds original tree exactly
Example 2
Input: root = [1,null,2,null,null,null,3]
Output: "1,null,2,null,null,null,3,..."
Constraints: 0 ≤ nodes ≤ 104  |  −1000 ≤ Node.val ≤ 1000
Try Examples
Custom:
Approach
BFS Serialize → String, then BFS Deserialize → Tree
Serialize: BFS level-order, appending node values or "null" for missing. Deserialize: split by comma, create root, then BFS — for each dequeued parent, consume next two tokens as left/right children.
Phase 1: SERIALIZE
Phase 2: DESERIALIZE
Binary Tree (Original)
In Queue
Processing
Serialized
Restored
Newly Built
Serialized String
Tokens will appear here during serialization…
BFS Queue
Queue is empty
Variables
Phase
Token idx
Queue size
0
Nodes built
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Tree Serialized and Deserialized!
Algorithm Steps
1
Serialize: BFS level-order, "null" for missing nodes
2
Poll each node, append val (or "null") to string
3
Enqueue left and right children (even if null)
4
Deserialize: split string by comma, BFS rebuild
5
Read token pairs as left/right for each parent node
Time
O(n)
Space
O(n)
Why It Works

BFS serialization produces level-order output including nulls. Deserializing BFS output works because we know each parent's children occupy exactly the next two positions in the token stream — null tokens mark absent children. The BFS queue keeps parents and children in perfect sync: each dequeued parent consumes exactly two tokens, and each non-null token produces exactly one new child to enqueue.