AlgoLounge

Serialize and Deserialize Binary Tree

hard

Leetcode 297. Serialize And Deserialize Binary Tree

Implement an algorithm to serialize and deserialize a binary tree.

Serialization is the process of converting an in-memory structure into a sequence of bits so that it can be stored or sent across a network to be reconstructed later in another computer environment.

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. There is no additional restriction on how your serialization/deserialization algorithm should work.

**Note:** The input/output format in the examples is the same as how NeetCode serializes a binary tree. You do not necessarily need to follow this format.

Examples

Example 1

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

Example 2

Input:  root = []
Output: []

Constraints

  • `0 <= The number of nodes in the tree <= 1000`.
  • `-1000 <= Node.val <= 1000`

How the tests work: trees are written as level-order arrays — [1,null,2] is a root 1 with a right child 2. Your function receives real TreeNode objects, and the tree you return is read back into an array.

TypeScript
Loading editor…
List of test cases (10)
Case 1
root = [1,2,3,null,null,4,5]
Case 2
root = []
Case 3
root = [1]
Case 4
root = [1,2]
Case 5
root = [1,null,2]
Case 6
root = [5,3,7,2,4,6,8]
Case 7
root = [1,2,3,4,5,6,7]
Case 8
root = [10,5,15,null,null,12,20]
Case 9
root = [1,2,3,null,4,null,5]
Case 10
root = [8,3,10,1,6,null,14,null,null,4,7,13]