Tutorialspoint
Problem
Solution
Submissions

Serialize and Deserialize Binary Tree

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java 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 to be reconstructed later. In this problem, you need to design an algorithm to serialize a binary tree into a string and deserialize that string back into the original tree structure.

Example 1
  • Input: root = [1,2,3,null,null,4,5]
  • Output: [1,2,3,null,null,4,5]
  • Explanation: The tree looks like:

    Serialize and Deserialize Binary Tree with root node 1


    • Using preorder traversal, we can serialize this as "1,2,#,#,3,4,#,#,5,#,#". When we deserialize this string, we should get back the original tree structure.
Example 2
  • Input: root = []
  • Output: []
  • Explanation: We need to serialize an empty tree. The empty tree can be represented as an empty string or a special marker. When we deserialize this, we should get back 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 serialization and deserialization, where n is the number of nodes
  • Space Complexity: O(n)
Binary TreePhillipsOracle
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 a recursive approach for both serialization and deserialization
  • For serialization, consider using preorder traversal (root, left, right)
  • Use a special marker (like "#" or "null") to denote null nodes
  • For deserialization, process the serialized data in the same order as it was created
  • Consider using a queue or other data structure to help process the serialized string
  • Make sure to handle edge cases like an empty tree

Steps to solve by this approach:

 Step 1: Define constants for null node representation and delimiter to separate values in the serialized string.

 Step 2: For serialization, use a recursive preorder traversal approach (root, left, right).
 Step 3: Append each node's value to a StringBuilder, followed by the delimiter. For null nodes, append the null symbol.
 Step 4: For deserialization, split the input string by the delimiter to get individual values.
 Step 5: Use a queue to process these values in the order they were serialized.
 Step 6: Recursively build the tree: create a node with the current value, then recursively build its left and right subtrees.
 Step 7: Handle edge cases like empty trees by checking for null or empty input string.

Submitted Code :