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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search 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.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classCodec { public: intdecodeInt(string &s, int begin){ int v = 0; for(int i = 0; i < 4; i++){ int t = s[i + begin]; v |= ((t & 0xff) << (i << 3)); } return v; } stringencodeInt(int v){ string s; for(int i = 0; i < 4; i++){ s.push_back(v & 0xff); v >>= 8; } return s; }
// Encodes a tree to a single string. stringserialize(TreeNode* root){ return encodeDFS(root); } stringencodeDFS(TreeNode *node){ if(!node) returnstring(); return encodeInt(node->val) + encodeDFS(node->left) + encodeDFS(node->right); }
// Decodes your encoded data to tree. TreeNode* deserialize(string data){ //cout<<data<<endl; return deserializeHelper(data, 0, data.length()); } TreeNode* deserializeHelper(string &data, int left, int right){ if(left == right) returnnullptr; int v = decodeInt(data, left); //cout<<v<<endl; TreeNode *node = new TreeNode(v); int mid = right; for(int i = left + 4; i < right; i += 4){ int t = decodeInt(data, i); if(t > v) { mid = i; break; } } node->left = deserializeHelper(data, left + 4, mid); node->right = deserializeHelper(data, mid, right); return node; } };
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));