AcWing 50. 序列化二叉树(用库函数考虑负数)简单有效
原题链接
困难
作者:
梵高先生
,
2020-05-11 19:29:34
,
所有人可见
,
阅读 811
正反序列化 C++代码
对于处理负数的问题,我只想说使用库函数,省时省力考虑还周全,何乐而不为?
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root == NULL) return "#!";
string res = "";
res += to_string(root->val);
res += "!";
res += serialize(root->left);
res += serialize(root->right);
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
//cout <<data<<endl;
queue<string> q;
string temp = "";
for(int i = 0 ; i < data.size(); i ++){
if(data[i] != '!'){
temp += data[i];
}
else{
q.push(temp);
//cout <<temp<<" ";
temp = "";
}
}
return buildtree(q);
}
TreeNode * buildtree(queue<string> &q){ //注意此处的引用
string temp = q.front();
q.pop();
if(temp == "#"){
return NULL;
}
else{
TreeNode * t = new TreeNode(stoi(temp));
t->left = buildtree(q);
t->right = buildtree(q);
return t;
}
}
};