Design an algorithm to serialize a binary tree to a string and deserialize that string back into the original tree structure.
For example:
1
/ \
2 3
/ \
4 5One possible serialization: "1,2,null,null,3,4,null,null,5,null,null"
Your serialization format must capture the complete structure of the tree, including null children, so that deserialization produces an identical tree.
What traversal order would you use? How do you handle null nodes? How does deserialization reconstruct the tree from the string?
Explain your approach and analyze the time and space complexity.
How to approach it
- Hint 1
Pre-order traversal (root, left, right) is a natural choice because the root is processed first, making reconstruction straightforward.
- Hint 2
Include null markers in the serialized string to indicate absent children. Without them, you cannot distinguish different tree structures.
- Hint 3
For deserialization, use a queue or index pointer to consume tokens one by one. Each token either creates a node or represents a null child.
Ready to answer it out loud?
Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.
Practising needs an invite code. Join the waitlist and we’ll send you one.