PIXELBANKv9.1.0
Menu

Serialize and Deserialize Binary Tree

Design an algorithm to serialize a binary tree to a string and deserialize it back.

Input: level-order array (comma-separated, 'null' for missing). Output: serialized then deserialized back to level-order.

Example:

Input:
1,2,3,null,null,4,5
Output:
1 2 3 null null 4 5
Reasoning:
  • The input string 1,2,3,null,null,4,5 is first split into an array of node values, representing a level-order traversal of the binary tree.
  • A binary tree is constructed from this array, where null values indicate missing nodes:
    • Root node: 1
    • Left child of 1: 2
    • Right child of 1: 3
    • Left child of 2: null
    • Right child of 2: null
    • Left child of 3: 4
    • Right child of 3: 5
  • The tree is then serialized to a string, which in this case is the same as the input string since the serialization is based on level-order traversal.
  • The serialized string is then deserialized back to a binary tree, resulting in the same tree structure as before.
  • The final output is obtained by performing a level-order traversal of the deserialized tree, resulting in 1 2 3 null null 4 5.

Constraints:

  • 0 <= number of nodes <= 10^4
  • -1000 <= Node.val <= 1000
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.