反序列化:输入为字符串,根据输入创建二叉树
序列化:输入为二叉树,输出为字符串
struct TreeNode//定义二叉树
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode() :left(nullptr), right(nullptr) {}
TreeNode(int x) :val(x), left(nullptr), right(nullptr) {}
};
class Codec {
public:
void preorder(TreeNode* root, string& res) {//先序遍历将二叉树序列化
if (!root) {
res += "null,";
return;
}
res += to_string(root->val) + ",";
preorder(root->left, res);
preorder(root->right, res);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
preorder(root, res);
res.insert(res.begin(), '[');
res[res.size() - 1] = ']';
return res;
}
queue<string> split(string& data) {//将字符串分割为单个字符
int start = 1;
queue<string> res;
std::string::size_type pos;
while (1) {
pos = data.find(',', start);
if (pos == string::npos)break;
res.push(data.substr(start, pos - start));
start = pos + 1;
}
res.push(data.substr(start, 1));
return res;
}
TreeNode* deserialize(queue<string>& str) {
if (str.empty())return NULL;
string first = str.front();
str.pop();
if (first == "null")return NULL;
TreeNode* root = new TreeNode(stoi(first));//创建根节点
queue<TreeNode*>q;
q.push(root);
TreeNode* bt;
while (!q.empty()) {
bt = q.front();
q.pop();
if (!bt)continue;
if (!str.empty()) {//构造左孩子
string first = str.front();
str.pop();
if (first == "null")bt->left = nullptr;
else bt->left = new TreeNode(stoi(first));
q.push(bt->left);
}
else {
bt->left = nullptr;
}
if (!str.empty()) {//构造右孩子
string first = str.front();
str.pop();
if (first == "null")bt->left = nullptr;
else bt->right = new TreeNode(stoi(first));
q.push(bt->right);
}
else {
bt->right = nullptr;
}
}
return root;
}
TreeNode* deserialize(string data) {
queue<string>str;
str = split(data);
return deserialize(str);
}
};