class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own “deserialize” method later.
*/
int strToint(string &svalue)
{
stringstream ss;
ss << svalue;
int ivalue;
ss >> ivalue;
return ivalue;
}
//整形转换为字符串
string intTostr(int &ivalue)
{
stringstream ss;
ss << ivalue;
string svalue;
ss >> svalue;
return svalue;
}
string serialize(TreeNode * root) {
// write your code here
if(root==NULL)
return “#!”;
string svalue = intTostr(root->val);
string res=svalue+"!";
res+=serialize(root->left);
res+=serialize(root->right);
return res;
}
vector split(string str,string pattren){
string::size_type pos;
vector result;
str+=pattren;
int size=str.size();
for(int i=0;i<size;i++){
pos=str.find(pattren,i);
if(pos<size){
string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattren.size()-1; }
}
return result;
}
TreeNode * deserialize(string &data) {
// write your code here
vector values;
values=split(data,"!");
int size=values.size();
queue valueq;
for(int i=0;i<size;i++){
valueq.push(values[i]);
}
return inverse_sequence(valueq);
}
TreeNode *inverse_sequence(queue&valueq){
string value=valueq.front();
valueq.pop();
if(value=="#")
return NULL;
int ivalue = strToint(value);
TreeNode *node=new TreeNode(ivalue);
node->left=inverse_sequence(valueq);
node->right=inverse_sequence(valueq);
return node;
}
};