Serialize and Deserialize

Solution for Leetcode 449.

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 encode and decode BST.

leetcode 449 : Serialize and Deserialize BST
刚开始觉得怎么和271类似,于是呼写了个一毛一样的,居然过了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 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:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return "#";
return to_string(root->val) + "," + serialize(root->left) + "," + serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
return help(data);
}
private:
TreeNode* help(string& data){
if (data[0] == '#'){
if (data.size() > 1){
data = data.substr(2);
}
return nullptr;
}
auto root = new TreeNode(helper(data));
root->left = help(data);
root->right = help(data);
return root;
}
int helper(string& data){
int pos = data.find(',');
int num = stoi(data.substr(0,pos));
data = data.substr(pos + 1);
return num;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

不小心点开了discuss里一个用c++的高票,果然牛逼啊。基本思路依旧是preorder遍历,但是inline,memcpy的应用再加上用4个char来代替string,以及利用binary serch tree 的特性免去了对string的解析和内存的浪费,按照这个思路重新写一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
dfs(root,res);
return res;
}
// Decodes your encoded X`data to tree.
TreeNode* deserialize(string data) {
int pos = 0;
return reconstruct(data, pos, INT_MIN, INT_MAX);
}
private:
inline void dfs(TreeNode* root,string &res){
if(!root) return;
char buf[4];
memcpy(buf,&(root->val),sizeof(int));
for(const auto& c : buf) res.push_back(c);
dfs(root->left,res);
dfs(root->right,res);
}
inline auto reconstruct(string data, int &pos, int min_v, int max_v) -> TreeNode*{
if (pos >= data.size()) return nullptr;
int val;
memcpy(&val,&data[pos],sizeof(int));
if (val > max_v || val < min_v){
return nullptr;
}
auto root = new TreeNode(val);
pos += sizeof(int);
root->left = reconstruct(data,pos,min_v,val);
root->right = reconstruct(data,pos,val,max_v);
return root;
}
};

又一次感受到了C++和C对底层性能的高效应用以及编译器的强大。