DSA AnimatorDSA animations
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.

How to solve Serialize and Deserialize Binary Tree

LeetCode 297 · Hard · Tree · Pattern: Preorder with Null Markers

Why the obvious approach is slow

Storing only the preorder values is not enough, because different shapes can share the same preorder. Recording the empty children as well makes the shape unique.

The key idea

To serialize, do a preorder traversal. Write each value, and write a hash for every null child. To deserialize, read the tokens in the same preorder. A hash means null, and any number creates a node whose left and right children are read next, in that order.

Remember

Preorder plus null markers describes a tree completely. Read the tokens back in exactly the order you wrote them.

Run the animation above on your own input, or watch the 2:09 video explanation of Serialize and Deserialize Binary Tree with a dry run and Java code.

More Tree problems