Coding Interview PatternsSerialize and Deserialize Binary Tree
HardTree Depth-First Search

Serialize and Deserialize Binary Tree

Explanation & Solution

Description

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Examples

Example 1:

```tree

[1, 2, 3, null, null, 4, 5]

`

Input:root = [1, 2, 3, null, null, 4, 5]
0
1
1
2
2
3
3
null
4
null
5
4
6
5
Output:[1, 2, 3, null, null, 4, 5]
0
1
1
2
2
3
3
null
4
null
5
4
6
5

Explanation: The tree is serialized to "[1,2,3,null,null,4,5]" and then deserialized back to the same tree structure.

Input: root = []

Output: []

Explanation: An empty tree serializes to "[]" and deserializes back to null.

```tree

[1]

`

Input:root = [1]
0
1
Output:[1]
0
1

Explanation: A single node tree serializes and deserializes correctly.

Constraints

  • The number of nodes in the tree is in the range [0, 10⁴]
  • -1000 <= Node.val <= 1000

Approach

Tree Depth-First Search pattern

Key Insight

  • BFS serialization produces a level-order array that naturally maps to the standard tree format [1, 2, 3, null, null, 4, 5]
  • Deserialization mirrors this: process values in pairs (left, right) for each node in BFS order
Time
O(n) for both serialize and deserialize
Space
O(n) for the queue and output

Visualization

Input:
DFS Traversal[1, 2, 3, 4, 5]
12345
output0

Press play to start DFS traversal

CurrentIn stackComplete
11 steps

Solution Code