Serialize and Deserialize Binary Tree

Hard

Description

Design an algorithm to serialize and deserialize a binary tree. Serialization is converting a tree to a string. Deserialization is reconstructing the tree from the string.

Examples

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

Serialize to string, then deserialize back to the same tree.

Input:root = []
Output:[]
Explanation:

Empty tree.

Input:root = [-5,3,-8,null,7,null,null,2,null]
Output:[-5,3,-8,null,7,null,null,2,null]
Explanation:

A tree with negative values and an unbalanced structure. The root is -5, with left child 3 (which has right child 7, and 7 has left child 2) and right child -8. After serialization and deserialization, the tree structure with all negative and positive values is preserved exactly.

Constraints

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

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!