Serialize and Deserialize Binary Tree

HardArrayStringMathLinked ListTreeBinary Tree

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. Return the result as an array.

Examples

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

Tree with root 1, left child 2, right child 3 (with children 4,5) serializes and reconstructs identically.

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

Empty tree serializes to [] and deserializes back to an empty tree.

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

Unbalanced tree: root -5, left subtree 3->7->2, right child -8. Structure preserved through serialize/deserialize.

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!