class Codec {
public:
string serialize(TreeNode* root) {
string s;
serialize(root, s);
return s;
}
TreeNode* deserialize(string data) {
int pos = 0;
return deserialize(data, INT_MIN, INT_MAX, pos);
}
private:
void serialize(TreeNode* root, string &s) {
if (!root) return;
s += to_string(root->val) + "#";
serialize(root->left, s);
serialize(root->right, s);
}
TreeNode* deserialize(string &s, int l, int r, int &pos) {
if (pos >= s.size()) return NULL;
int lastpos = pos;
int val = 0;
while (s[pos] != '#')
val = val * 10 + s[pos++] - '0';
pos++;
if (l <= val && val <= r) {
TreeNode* root = new TreeNode(val);
root->left = deserialize(s, l, val, pos);
root->right = deserialize(s, val, r, pos);
return root;
}
pos = lastpos;
return NULL;
}
};