Leetcode—297. 二叉树的序列化与反序列化【困难】
2024每日刷题(148)
Leetcode—297. 二叉树的序列化与反序列化
实现代码
/**
* 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 ans;
function<void(TreeNode*)> preorder = [&](TreeNode* root) {
if(root == nullptr) {
ans += "null ";
return;
}
ans += to_string(root->val) + " ";
preorder(root->left);
preorder(root->right);
};
preorder(root);
return ans;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream iss(data);
queue<string> q;
for(string s; iss >> s;) {
q.push(s);
}
function<TreeNode*()> preorder = [&]() {
string node = q.front();
q.pop();
if(node == "null") {
return (TreeNode*)nullptr;
}
TreeNode* newNode = new TreeNode(stoi(node));
newNode->left = preorder();
newNode->right = preorder();
return newNode;
};
return preorder();
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!
原文地址:https://blog.csdn.net/qq_44631615/article/details/140668316
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!