/**
* 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:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) {
return "";
}
vector<int> v;
DoSerialize(root, v);
int len = sizeof(int) * v.size();
return string((char *)&v[0], len);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) {
return NULL;
}
int *x = (int*)&data[0];
return DoDeserialize(x, x + (data.size() / (sizeof(int))));
}
private:
void DoSerialize(TreeNode *root, vector<int> &ret) {
if (!root) {
return;
}
ret.push_back(root->val);
DoSerialize(root->left, ret);
DoSerialize(root->right, ret);
}
TreeNode *DoDeserialize(int *cur, int *limit) {
if (cur == limit) {
return NULL;
}
int val = *cur;
auto *root = new TreeNode(val);
int *right = find_if(cur, limit, [val](int i) {
return i > val;
});
root->left = DoDeserialize(cur+1, right);
root->right = DoDeserialize(right, limit);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));