
Problem
Solution
Submissions
Serialize and Deserialize Binary Tree
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a JavaScript program to serialize a binary tree to a string and deserialize a string back to a binary tree. Serialization is the process of converting a data structure into a format that can be stored or transmitted, while deserialization is the reverse process. The serialized string should be able to reconstruct the exact same binary tree structure.
Example 1
- Input: root = [1,2,3,null,null,4,5]
- Output: "1,2,null,null,3,4,null,null,5,null,null"
- Explanation:
Step 1: The binary tree has root node 1 with left child 2 and right child 3.
Step 2: Node 2 has no children (both left and right are null).
Step 3: Node 3 has left child 4 and right child 5.
Step 4: Nodes 4 and 5 have no children.
Step 5: The serialization uses preorder traversal with null markers.
Example 2
- Input: root = [1,2]
- Output: "1,2,null,null,null"
- Explanation:
Step 1: The binary tree has root node 1 with only a left child 2.
Step 2: Node 2 has no children (both left and right are null).
Step 3: The right child of root is null.
Step 4: The serialization captures this structure with null markers.
Constraints
- The number of nodes in the tree is in the range [0, 10^4]
- -1000 ≤ Node.val ≤ 1000
- Your serialize and deserialize functions should be stateless
- The serialized string should be as compact as possible
- Time Complexity: O(n) for both serialize and deserialize
- Space Complexity: O(n)
Editorial
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. | ||||
Solution Hints
- Use preorder traversal (root, left, right) for serialization
- Include null markers in the serialized string to preserve tree structure
- Use a delimiter (like comma) to separate values in the string
- For deserialization, use the same traversal order and a pointer/index
- Recursively build the tree while consuming the serialized data
- Handle null values properly during reconstruction
- Consider using a queue or array with index tracking for deserialization