在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
函數中,我們構建了一棵樹,將其序列化后再反序列化,最后輸出反序列化后的樹節點值。