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.
对二叉搜索树的序列化和反序列化
解题思路:
(1)序列化:
利用先序遍历的顺序遍历节点进行序列化为一个字符串,用‘#’间隔每个元素。
其中用到将int类型转换为string类型。
(2)反序列化:
利用字符串构造二叉树,先构造出每个节点,再将节点插入到二叉树中。
其中用到将string类型转换为int类型。
/**
* 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:
string IntToString(int val)
{
string tmp;
while(val != 0)
{
tmp += (val % 10 + '0');
val /= 10;
}
string str;
for(int i = tmp.size() - 1; i >= 0; --i)
{
str += tmp[i];
}
return str;
}
void PreOrder(TreeNode *root, string &str)
{
if(!root)
return;
str += IntToString(root->val) + '#';
PreOrder(root->left, str);
PreOrder(root->right, str);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string str;
PreOrder(root, str);
return str;
}
void Insert(TreeNode *root, TreeNode *node)
{
if(root->val > node->val)
{
if(!root->left)
root->left = node;
else
Insert(root->left, node);
}
else if(root->val < node->val)
{
if(!root->right)
root->right = node;
else
Insert(root->right, node);
}
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size() == 0)
return NULL;
vector<TreeNode *> vec;
int val = 0;
for(int i = 0; i < data.size(); ++i)
{
if(data[i] != '#')
{
val = val * 10 + data[i] - '0';
}
else
{
vec.push_back(new TreeNode(val));
val = 0;
}
}
for(int i = 1; i < vec.size(); ++i)
{
Insert(vec[0], vec[i]);
}
return vec[0];
}
};