Easy To Understand C++ Solution Using PreOrder Traversal and iostringstream
Because of BST, so we can use PreOrder Traversal to rebuild the tree, so do with serialize and deserialize. After using iostringstream, we can easily get the va
Because of BST, so we can use `PreOrder Traversal` to rebuild the tree, so do with serialize and deserialize. After using `iostringstream`, we can easily get the values and build the tree.\n\n```\nclass Codec \n{\npublic:\n\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) \n    {\n        ostringstream out;\n        mySerialize(root, out);\n        return out.str();\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* deserialize(string data) \n    {\n        if(data == "") return NULL;\n        istringstream in(data);\n        return myDeserialize(in);\n    }\nprivate:\n\tvoid mySerialize(TreeNode* root, ostringstream &out)\n\t{\n\t\tif(root == NULL) return;\n\t\tout << root->val << " ";\n\t\tmySerialize(root->left, out);\n\t\tmySerialize(root->right, out);\n\t}\n\n\tTreeNode* myDeserialize(istringstream &in)\n\t{\n\t\tstring val;\n\t\tin >> val;\n\t\tTreeNode *root = new TreeNode(stoi(val));\n\t\twhile(in >> val)\n\t\t\tbuildTree(root, stoi(val));\n\t\treturn root;\n\t}\n\n\tvoid buildTree(TreeNode* root, int n)\n\t{\n\t\tif(root->val > n)\n\t\t{\n\t\t\tif(root->left == NULL)\n\t\t\t\troot->left = new TreeNode(n);\n\t\t\telse\n\t\t\t\tbuildTree(root->left, n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(root->right == NULL)\n\t\t\t\troot->right = new TreeNode(n);\n\t\t\telse\n\t\t\t\tbuildTree(root->right, n);\n\t\t}\n\t}\n};\n```
[]