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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You 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.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classCodec { voidsHelper(TreeNode* node, string& res){ if(!node) res += "#,"; else { res += to_string(node->val) + ','; sHelper(node->left, res); sHelper(node->right, res); } } intparseNum(string& s, int& p){ int res = 0; while(p < s.length() andisdigit(s[p])) { res = res * 10 + (s[p++] & 0b1111); } p++; return res; } TreeNode* dHelper(string& d, int& i){ if(i >= d.length() or d[i] == '#') { i += 2; returnNULL; } TreeNode* node = newTreeNode(parseNum(d,i)); node->left = dHelper(d,i); node->right = dHelper(d,i); return node; } public:
// Encodes a tree to a single string. string serialize(TreeNode* root){ string res = ""; sHelper(root, res); return res; }
// Decodes your encoded data to tree. TreeNode* deserialize(string data){ int p = 0; returndHelper(data, p); } };
// 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;