Tutorialspoint
Problem
Solution
Submissions

Serialize and Deserialize a Binary Tree

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C# program to serialize and deserialize a binary tree. Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection. Deserialization is the process of reconstructing the data structure from this sequence.

Example 1
  • Input: root = [1,2,3,null,null,4,5]
  • Output: [1,2,3,null,null,4,5]
  • Explanation:
    • The binary tree with root node value 1, left child value 2, and right child value 3.
    • The right child of 2 is null and the left child of 3 is 4, and its right child is 5.
Example 2
  • Input: root = []
  • Output: []
  • Explanation:
    • An empty tree is serialized as an empty string and deserialized as an empty tree.
Constraints
  • The number of nodes in the tree is in the range [0, 10^4]
  • -1000 <= Node.val <= 1000
  • Time Complexity: O(n) for both serialize and deserialize
  • Space Complexity: O(n) for both serialize and deserialize
Binary TreeGooglePwC
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 pre-order traversal to serialize the binary tree
  • Use a special marker like "null" to represent null nodes
  • For deserialization, reconstruct the tree by following the same pre-order traversal
  • Use a queue or list and index to keep track of the current position during deserialization

Steps to solve by this approach:

 Step 1: For serialization, use a level-order traversal (BFS) to convert the tree into a string representation.
 Step 2: Use a queue to perform the level-order traversal, including null nodes.
 Step 3: Join the values with commas and surround with brackets to create the serialized string.
 Step 4: For deserialization, parse the string to extract node values and reconstruct the tree.
 Step 5: Use a queue to reconstruct the tree level by level, following the same order as in serialization.
 Step 6: For each node dequeued, create its left and right children (if they exist) and enqueue them.
 Step 7: Return the reconstructed root node.

Submitted Code :