Design Gurus Logo
Serialize and Deserialize Binary Tree (hard)
Go Back

Problem Statement

Given a binary tree, your task is to create two functions.

one for serializing the tree into a string format and another for deserializing the string back into the tree.

The serialized string should retain all the tree nodes and their connections, allowing for reconstruction without any loss of data.

Examples

  1. Example 1:

    • Input: [1,2,3,null,null,4,5]
    • Expected Output: [1,2,3,null,null,4,5]
    • Justification: The tree has the structure:
        1
       / \
      2   3
         / \
        4   5
      
      When serialized and then deserialized, it should retain the exact same structure.
  2. Example 2:

    • Input: [1,null,2,3]
    • Expected Output: [1,null,2,3]
    • Justification: The tree has the structure:
        1
         \
          2
         /
        3
      
      When serialized and then deserialized, it should retain the exact same structure.
  3. Example 3:

    • Input: [5,4,7,3,null,null,null,2]
    • Expected Output: [5,4,7,3,null,null,null,2]
    • Justification: The tree has the structure:
             5
           /   \
          4     7
         /     
        3    
       /
      2
      

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000

Try it yourself

Try solving this question here:

Python3
Python3