Skip to content

Instantly share code, notes, and snippets.

@selfboot
Created April 27, 2016 00:53
Show Gist options
  • Select an option

  • Save selfboot/051b7c9bf2dbeb457ea619f34f5d27a1 to your computer and use it in GitHub Desktop.

Select an option

Save selfboot/051b7c9bf2dbeb457ea619f34f5d27a1 to your computer and use it in GitHub Desktop.
Serialize and Deserialize Binary Tree
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
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) {
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 nullptr;
TreeNode* root = new TreeNode(stoi(val));
root->left = deserialize(in);
root->right = deserialize(in);
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment