Tutorialspoint
Problem
Solution
Submissions

Serialize and Deserialize Binary Tree

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

Write a C program to serialize a binary tree to a string and deserialize the string back to the original tree structure. Serialization is the process of converting a data structure into a sequence of bits so that it can be stored or transmitted and reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree.

Example 1
  • Input: root = [1,2,3,null,null,4,5]
  • Output: [1,2,3,null,null,4,5]
  • Explanation:
    • The binary tree is serialized to string representation.
    • The string is then deserialized back to the original tree.
    • Both trees should have identical structure and values.

Example 2
  • Input: root = []
  • Output: []
  • Explanation:
    • An empty tree is serialized to empty representation.
    • Deserializing empty representation gives back empty tree.
    • Both input and output are empty trees.

Constraints
  • The number of nodes in the tree is in the range [0, 10^4]
  • -1000 ≤ Node.val ≤ 1000
  • Your serialization should be compact and readable
  • Time Complexity: O(n) for both serialize and deserialize
  • Space Complexity: O(n)
Binary TreeHCL TechnologiesPhillips
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 preorder traversal for serialization to maintain tree structure
  • Use a delimiter (like comma) to separate node values in the string
  • Use a special marker (like "null") to represent null nodes
  • For deserialization, parse the string and recursively build the tree
  • Use a global index or pointer to track current position during parsing

Steps to solve by this approach:

 Step 1: For serialization, use preorder traversal to visit nodes in a specific order.
 Step 2: Convert each node's value to string and append to result with delimiter.
 Step 3: Use special marker "null" to represent null nodes in the serialized string.
 Step 4: For deserialization, tokenize the serialized string using delimiter.
 Step 5: Use recursive approach with global token index to track current position.
 Step 6: Build tree nodes by parsing tokens in preorder sequence.
 Step 7: Return the root of the reconstructed binary tree.

Submitted Code :