Tutorialspoint
Problem
Solution
Submissions

Serialize and Deserialize a Binary Tree

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 10

Write two Python functions to serialize and deserialize a binary tree. Serialization is the process of converting a data structure or object into a sequence of bits (or string) so that it can be stored or transmitted and reconstructed later. Deserialization is the reverse process.

Example 1
  • Input:

    Serialize and Deserialize a Binary Tree with three levels

  • Output: After serialization and deserialization, the tree should be identical to the original tree.
  • Explanation:
    • Step 1: Traverse the binary tree and serialize it into a string representation.
    • Step 2: Store or transmit the serialized string.
    • Step 3: Deserialize the string back into the original binary tree structure.
    • Step 4: The reconstructed tree is structurally and functionally identical to the original.
Example 2
  • Input:

     Serialize and Deserialize a Binary Tree with two levels

  • Output: After serialization and deserialization, the tree should be identical to the original tree.
  • Explanation:
    • Step 1: Serialize the tree structure starting from root.
    • Step 2: Deserialize to reconstruct the left child and maintain tree hierarchy.
Constraints
  • Number of nodes in the tree is in the range [0, 10^4]
  • -1000 ≤ Node.val ≤ 1000
  • Time Complexity: O(n), where n is the number of nodes
  • Space Complexity: O(n)
StringsAlgorithmsBinary TreeAccentureEY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use level-order traversal (BFS) for serialization
  • Use preorder traversal (DFS) for serialization
  • Use "null" or special marker for null nodes
  • Use a queue for level-order traversal during deserialization
  • Split the string representation for parsing

Steps to solve by this approach:

 Step 1: Create a TreeNode class with value and left/right child pointers.
 Step 2: For serialization, use a preorder traversal (root, left, right) with "null" markers for empty nodes.
 Step 3: Implement a recursive DFS helper function that appends node values to a result list.
 Step 4: Join the values with commas to create a serialized string representation.
 Step 5: For deserialization, split the string by commas and create an iterator.
 Step 6: Implement a recursive function that constructs nodes based on the preorder sequence.
 Step 7: Return null when encountering "null" values, otherwise create a new TreeNode.

Submitted Code :