(1)每个节点结束,打上结束符’!’,如"12!",“8!“等
(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) {
string res;
if(root == nullptr)
return res;
traversal(root,res);
return res;
}
// Decodes your encoded data to tree.
// 前序遍历二叉树的反序列化
TreeNode* deserialize(string data) {
if(data.empty())
return nullptr;
//先将带"!"结束符的字符串,转为无"!"的数组
vector<string> value;
int i = 0;
while(i<data.size())
{
int start = i;
while(data[i]!='!')
++i;
value.push_back(data.substr(start,i-start));
++i;
}
// 依次将数组中的值构造节点
TreeNode* root = nullptr;
int start = 0;
deser(value,root,start);
return root;
}
// 采用先序遍历的反序列化,先构造根,再构造left,再构造right
void deser(vector<string> &value, TreeNode* &root,int &start)
{
// 表明不是空节点
if(value[start] != "#")
{
root = new TreeNode(stoi(value[start]));
root->left = nullptr;
root->right = nullptr;
}
// 空节点
else
{
root = nullptr;
return;
}
// 序列化数组遍历完了
if(start>=value.size())
return;
// 构造左子树
deser(value,root->left,++start);
// 构造右子树
deser(value,root->right,++start);
}
void traversal(TreeNode* root,string &res)
{
if(root == nullptr)
{
res += "#!";
return;
}
res += to_string(root->val);
res.push_back('!');
traversal(root->left,res);
traversal(root->right,res);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));