Created
April 27, 2016 00:53
-
-
Save selfboot/051b7c9bf2dbeb457ea619f34f5d27a1 to your computer and use it in GitHub Desktop.
Serialize and Deserialize Binary Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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