题目描述
描述
设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。
如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:
3
9 20
/
15 7
进行BFS遍历得到的。
直接上代码
class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
string serialize(TreeNode * root)
{
// write your code here
string res;
if(root==NULL) return res+="#,";
res+=to_string(root->val);
res+=",";
res+=serialize(root->left);
res+=serialize(root->right);
return res;
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
TreeNode * deserialize(string &data)
{
// write your code here
int size = data.size();
if (size == 0) return NULL;
vector<string>v;
for (int i = 0; i < size;) {
if(data[i]!=','&&data[i]!='#'){
string s;
while (i<size&&data[i] != ','&&data[i]!='#') {
s += data[i];
i++;
}
v.push_back(s);
}
else if (data[i] == ',') i++;
else if (data[i++] == '#') v.push_back("#");
}
return helper(v);
}
TreeNode *helper(vector<string>&data) {
TreeNode *res;
if (data.empty()) return NULL;
string str=*data.begin();
data.erase(data.begin());
if (str== "#"){
return NULL;
}
int tmp;
tmp =atoi(str.c_str());
res = new TreeNode(tmp);
res->left = helper(data);
res->right = helper(data);
return res;
}
};