2024每日刷题(148)
Leetcode---297. 二叉树的序列化与反序列化
实现代码
cpp
/**
* 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));
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!