54. Serialize and Deserialize Binary Tree

Hard · Binary Tree

Design an algorithm to serialize a binary tree into a string and deserialize the string back into the original binary tree structure.

Serialization is the process of converting a tree into a string representation that can be stored or transmitted. Deserialization reconstructs the tree from that string. Your solution must handle all possible binary trees, including those with null nodes.

The serialization format is flexible—you may use any string format as long as your deserialize function can reconstruct the exact tree from your serialize output.

Examples

Example 1
Input: Tree: [1, 2, 3]
Output: Serialized: "1,2,3,null,null,null,null" → Deserialized: [1, 2, 3]
Explanation: A tree with root 1, left child 2, right child 3. The serialization uses level-order traversal with null markers for missing children. After deserialization, the tree structure is fully restored.
Example 2
Input: Tree: [1, null, 2]
Output: Serialized: "1,null,2,null,null" → Deserialized: [1, null, 2]
Explanation: A tree with root 1 and only a right child 2. Nulls represent missing nodes in level-order traversal.

Constraints