/**
* 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) {
string re;
if (root == NULL) re = "#,";
else re = to_string(root->val) + ',' + serialize(root->left) + serialize(root->right);
return re;
}
TreeNode *deserialize(queue<string>& dQ) {
if (dQ.size() <= 0) return NULL;
string chh = dQ.front();
dQ.pop();
TreeNode *node;
if (chh == "#") {
return NULL;
} else {
node = new TreeNode(atoi(chh.c_str()));
node->left = deserialize(dQ);
node->right = deserialize(dQ);
}
return node;
}
queue<string> splitStr(string data) {
queue<string> re;
int len = strlen(data.c_str());
if (len <= 0)
return re;
int lInex = 0;
int rIndex = 0;
while(rIndex < len) {
if (data[rIndex] == ','
&& rIndex != lInex) {
string tmpStr = data.substr(lInex, rIndex-lInex);
re.push(tmpStr);
lInex = rIndex+1;
}
rIndex++;
}
return re;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
queue<string> dVec = splitStr(data);
return deserialize(dVec);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));