題目
文章來源:http://www.zghlxwxcb.cn/news/detail-730092.html
297. 二叉樹的序列化與反序列化文章來源地址http://www.zghlxwxcb.cn/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;
}
};
到了這里,關(guān)于Leetcode 297. 二叉樹的序列化與反序列化的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!