int charToint(string c)
{
stringstream s;
s<<c;
int a;
s>>a;
return a;
}
string intTochar(int c)
{
stringstream s;
s<<c;
string a;
s>>a;
return a;
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s="";
if(root==NULL)
{
return s;
}
queue<TreeNode *>q;
q.push(root);
while(!q.empty())
{
int b;
b=q.front()->val;
vec.push_back(b);
if(q.front()->left!=NULL)
q.push(q.front()->left);
if(q.front()->right!=NULL)
q.push(q.front()->right);
s=s+intTochar(b);
s.push_back(',');
q.pop();
}
return s;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size()==0)
{ TreeNode *tem;
tem=NULL;
return tem ;
}
int k=0;
vector<int>vec;
for(k=0;k<data.size();k++)
{
string s="";
while(data[k]!=',')
{
s.push_back(data[k]);
k++;
}
vec.push_back(charToint(s));
s.clear();
}
TreeNode *r=new TreeNode;
TreeNode *temp;
r->val=vec[0];
r->left=r->right=NULL;
int i=1;
while(i<vec.size())
{ temp=r;
while(1)
{
if(temp->val>vec[i])
{
if(temp->left!=NULL)
temp=temp->left;
else
{
TreeNode *t=new TreeNode;
t->val=vec[i];
t->left=t->right=NULL;
temp->left=t;
break;
}
}
else
{
if(temp->right!=NULL)
temp=temp->right;
else
{
TreeNode *t=new TreeNode;
t->val=vec[i];
t->left=t->right=NULL;
temp->right=t;
break;
}
}
}
i++;
}
return r;
}