Serialize and Deserialize Binary Tree
Serialization is the process of converting a binary tree into a string so that it can be stored or transmitted.
Deserialization is the reverse process: converting the string back into the original binary tree.
Design an algorithm that can:
- Serialize a binary tree into a string.
- Deserialize the string back into the same binary tree.
The serialized representation should preserve both the node values and the structure of the tree.
Example Tree
1
/ \
2 3
/ \
4 5
One possible serialization is:
1,2,null,null,3,4,null,null,5,null,null
Example 1
Input
root = [1,2,3,null,null,4,5]
Output
Serialized: 1,2,null,null,3,4,null,null,5,null,null
Explanation
The tree is:
1
/ \
2 3
/ \
4 5
The serialization stores:
- 1 → root
- 2 → left child
- null → children of 2
- 3 → right child
- 4 and 5 → children of 3
- null values → missing children
The null markers are important because they preserve the structure of the tree.
Example 2
Input
root = []
Output
Serialized: null
Explanation
The tree is empty, so serialization produces a representation indicating that there is no root node.
Constraints
Hints:
Hint 1
You need to store both the values and the structure of the tree.
Hint 2
Use a special marker such as null for missing children.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 13, 2026
Last updated
Aug 14, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output