449. 序列化和反序列化二叉搜索树
class Codec {
public:
string serialize(TreeNode* root) {
vector<int>v;
postorder(root,v);
string s;
if(v.size()==0)return s;
for(int i=0;i<v.size()-1;i++)
s.append(to_string(v[i])+",");
s.append(to_string(v.back()));
return s;
}
void postorder(TreeNode *T,vector<int>&v)
{
if(!T)return;
if(T->left)postorder(T->left,v);
if(T->right)postorder(T->right,v);
v.push_back(T->val);
}
vector<string>split(string s,char c)
{
vector<string>v;
int t=0;
int start=0;
while(t<s.size())
{
while(t<s.size()&&s[t]==c)t++;
start=t;
while(t<s.size()&&s[t]!=c)t++;
if(start<s.size())v.push_back(s.substr(start,t-start));
}
return v;
}
TreeNode* deserialize(string data) {
if(data.size()==0)return nullptr;
vector<string>v=split(data,',');
int in[10010],pos[10010];
int cnt=0;
for(auto x:v)
{
in[cnt]=stoi(x);
pos[cnt]=stoi(x);
cnt++;
}
sort(in,in+cnt);
return create(cnt,in,pos);
}
TreeNode* create(int len,int *in,int *pos)
{
if(len<=0)return nullptr;
TreeNode *T=new TreeNode(pos[len-1]);
T->left=T->right=nullptr;
int i=0;
for(i=0;i<len;i++)
if(T->val==in[i])
break;
T->left=create(i,in,pos);
T->right=create(len-i-1,in+i+1,pos+i);
return T;
}
};
|