题目:
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.
思路:
这道题目本身并不难,基本思路是:序列化的时候就按照先序遍历输出即可。反序列化的时候,维护一个全局的索引。我们首先反序列化根节点,然后反序列化左子树,然后反序列化右子树,在递归调用反序列化函数的过程中索引值相应增加。
我开始的时候用逗号分隔不同结点上的值,后来发现网上的帖子中用空格分隔不同结点上的值更妙:这样就可以直接用istringstream,每次可以根据空格自动地解析出当前结点上的值,这样就连全局索引都不用了,代码变得更加简洁优雅。我把两段代码都贴上,读者可以体会用空格和istringstream的妙处。
代码:
1、用逗号分隔:
/**
* 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 == NULL) {
return string("#,");
}
else {
return to_string(root->val) + ',' + serialize(root->left) + serialize(root->right);
}
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.length() == 0) {
return NULL;
}
int index = 0;
return deserialize(data, index);
}
private:
TreeNode* deserialize(string &data, int &index) {
if (data[index] == '#') {
index += 2;
return NULL;
}
else {
int value = 0;
while (data[index] != ',') {
value = 10 * value + data[index++] - '0';
}
++index;
TreeNode *node = new TreeNode(value);
node->left = deserialize(data, index);
node->right = deserialize(data, index);
return node;
}
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
2、用空格分隔:
/**
* 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 " #";
}
string ans = " " + to_string(root->val);
return ans + serialize(root->left) + serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream is(data);
return DFS(is);
}
private:
TreeNode* DFS(istringstream &is) {
string str;
is >> str;
if(str == "#") {
return NULL;
}
TreeNode* root = new TreeNode(stoi(str));
root->left = DFS(is);
root->right = DFS(is);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));