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 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. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
1 / \ 2 3 / \ 4 5as
"[1,2,3,null,null,4,5]"
, just the same as
how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Credits:Special thanks to @Louis1992 for adding this problem and creating all test cases
basic idea
1) pre order/post order sequence with in order sequence can construct binary tree
we can store tree's pre/post order and in order sequence ,and reconstruct based on that
preorder#inorder or postorder#inorder
2) level order sequence
BFS solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
/*algorithm
regard tree as full binary tree
so i's child is 2i and 2i+1
*/
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
queue<TreeNode*>Q;
string s;
if(root)Q.push(root);
while(!Q.empty()){
int size = Q.size();
for(int i = 0;i < size;i++){
TreeNode* t = Q.front();Q.pop();
if(s.size() > 0)s += ",";
s += t?to_string(t->val):"#";
if(t){
Q.push(t->left);
Q.push(t->right);
}
}
}
return s;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size() < 1) return NULL;
queue<TreeNode*>Q;
int i = 0;
vector<string>vec;
TreeNode* root;
while(i < data.size()){
int j = i;
while(j < data.size()&&data[j] != ',')++j;
vec.push_back(data.substr(i,j-i));
i = j+1;
}
root = new TreeNode(atoi(vec[0].c_str()));
Q.push(root);
i = 1;
while(!Q.empty() && i < vec.size()){
int size = Q.size();
for(int j = 0;j < size;j++){
TreeNode* t = Q.front();Q.pop();
if(vec[i] != "#"){
t->left = new TreeNode(atoi(vec[i].c_str()));
Q.push(t->left);
}
++i;
if(vec[i] != "#"){
t->right = new TreeNode(atoi(vec[i].c_str()));
Q.push(t->right);
}
++i;
}
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));