69. Serialize and De-serialize BT

Serialization is 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 link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. Ensure that a binary tree can be serialized to a string, and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Example 1:

Input : root = [2, 1, 3]

Output : [2, 1, 3]

Example 2:

Input : root = [7, 3, 15, null, null, 9, 20]

Output : [7, 3, 15, null, null, 9, 20]

Now Your Turn!

Pick the correct output for the given input

Input : root = [10, 20, 30, 40, 50, 60]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • 0 <= Node.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
 
string serialize(TreeNode* root) {
}
 
TreeNode* deserialize(string data) {
}
};
 
 
/*
* Your Codec object will be instantiated and called as such:
* Codec* ser = new Codec();
* Codec* deser = new Codec();
* string tree = ser->serialize(root);
* TreeNode* ans = deser->deserialize(tree);
* return ans;
*/
Test Case

Input:

Root