在C++中实现树节点的序列化与反序列化可以通过递归遍历树的节点来实现。以下是一个简单的示例代码:
#include <iostream>
#include <sstream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 序列化树
void serialize(TreeNode* root, ostringstream& out) {
if (root) {
out << root->val << " ";
serialize(root->left, out);
serialize(root->right, out);
} else {
out << "# ";
}
}
// 反序列化树
TreeNode* deserialize(istringstream& in) {
string val;
in >> val;
if (val == "#") {
return NULL;
} else {
TreeNode* root = new TreeNode(stoi(val));
root->left = deserialize(in);
root->right = deserialize(in);
return root;
}
}
int main() {
// 构建一棵树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
// 序列化
ostringstream out;
serialize(root, out);
string serialized_str = out.str();
cout << "Serialized: " << serialized_str << endl;
// 反序列化
istringstream in(serialized_str);
TreeNode* new_root = deserialize(in);
// 输出反序列化后的树
cout << "Deserialized: " << new_root->val << " " << new_root->left->val << " " << new_root->right->val << " "
<< new_root->left->left->val << " " << new_root->left->right->val << endl;
return 0;
}
在上面的示例中,我们定义了一个TreeNode
结构体表示树节点,包含了节点的值和左右子树指针。serialize
函数用于序列化树,采用先序遍历的方式,将节点值以空格分隔的形式输出到ostringstream
对象中。deserialize
函数用于反序列化树,通过递归的方式构建树节点,并返回根节点指针。在main
函数中,我们构建了一棵树,将其序列化后再反序列化,最后输出反序列化后的树节点值。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C++模块化编程对开发者有何要求