我们使用二叉树的先序遍历来遍历整个树,对于空子树保存为#,恢复时也根据先序的顺序来恢复
297. Serialize and Deserialize Binary Tree
/**
* 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:
void serialize(TreeNode* root, ostringstream& out){
if(root == nullptr) {
out << "# ";
return;
}
out << root->val << ' ';
serialize(root->left, out);
serialize(root->right, out);
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
serialize(root, out);
return out.str();
}
TreeNode* deserialize(istringstream &in){
string data;
in >> data;
if(data == "#") return nullptr;
auto root = new TreeNode(stoi(data));
root->left = deserialize(in);
root->right = deserialize(in);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
return deserialize(in);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));