C++中如何实现树节点的序列化与反序列化

avatar
作者
猴君
阅读量:0

在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函数中,我们构建了一棵树,将其序列化后再反序列化,最后输出反序列化后的树节点值。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!