//先跟序列化(递归先根遍历)
class Codec {
public:
string serialize(TreeNode* root) {
ostringstream out;
serialize(root, out);
return out.str();
}
TreeNode* deserialize(string data) {
istringstream in(data);
return deserialize(in);
}
private:
void serialize(TreeNode* root, ostringstream& out) { //将root树序列化到out里
if (root) { //跟不为nullptr
out << root->val << ' '; //存根的值
serialize(root->left, out); //序列化左子树
serialize(root->right, out); //序列化右子树
} else {
out << "# "; //根为空就存#
}
}
TreeNode* deserialize(istringstream& in) {
string val;
in >> val;
if (val == "#") //如果为#则是nullptr
return nullptr;
TreeNode* root = new TreeNode(stoi(val)); //恢复根
root->left = deserialize(in); //反序列化。。这里没太明白
root->right = deserialize(in);
return root;
}
};
有先跟和层序两者序列化方式
先跟序列化又分递归和非递归两种方法