题目
文章来源:https://www.toymoban.com/news/detail-730092.html
297. 二叉树的序列化与反序列化文章来源地址https://www.toymoban.com/news/detail-730092.html
代码(9.30 首刷自解)
class Codec {
public:
string SEP = ",";
string NULL_STR = "#";
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root)
return NULL_STR + SEP;
string res = to_string(root->val) + SEP;
res += serialize(root->left);
res += serialize(root->right);
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
deque<string> nodes;
string tmp;
for(char& c : data) {
if(string(1,c) != SEP) {
tmp += c;
} else {
nodes.emplace_back(tmp);
tmp.clear();
}
}
return help(nodes);
}
TreeNode* help(deque<string>& nodes) {
auto front = nodes.front();
nodes.pop_front();
if(front == NULL_STR)
return nullptr;
auto root = new TreeNode(stoi(front));
root->left = help(nodes);
root->right = help(nodes);
return root;
}
};
到了这里,关于Leetcode 297. 二叉树的序列化与反序列化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!