Serialize and Deserialize Binary Tree

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Examples

Example 1:

12345

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

Output: [1, 2, 3, null, null, 4, 5]

Explanation: The tree is serialized to "[1,2,3,null,null,4,5]" and then deserialized back to the same tree structure.

Example 2:

Input: root = []

Output: []

Explanation: An empty tree serializes to "[]" and deserializes back to null.

Example 3:

1

Input: root = [1]

Output: [1]

Explanation: A single node tree serializes and deserializes correctly.

Constraints

  • The number of nodes in the tree is in the range [0, 10⁴]
  • -1000 <= Node.val <= 1000
Source: Tree Depth-First Search pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle