对二叉树转化方便使树在网络中的传输与重构。所以可以用不同的二叉树表达方式与遍历方式。
1、序列化
使用队列
2、反序列
使用队列
可能出现结点数据是负数,需要处理好前缀符号。
方法1:层次遍历
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x): val(x),left(NULL),right(NULL){}
};
const int INF=-1000000;
vector<int> split(string s,char c)
{
vector<int> vt;
int ans=0;
int i;
int flag=1;
for(i=0;s[i]!='\0';i++)
{
if(isdigit(s[i]))
ans=ans*10+s[i]-'0';
else if(s[i]=='-')
flag=-1;
else if(s[i]==c||s[i]==']')
{
if(!isdigit(s[i-1]))
{
if(i-4>=0)
{
string tmp=s.substr(i-4,4);
if(tmp=="null")
vt.push_back(INF);
}
}
else
{
ans=ans*flag;
vt.push_back(ans);
ans=0;
flag=1;
}
}
}
return vt;
}
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s="[";
queue<TreeNode*> q;
if(root!=NULL)
{
q.push(root);
s+=to_string(root->val);
s+=",";
}
TreeNode* node=NULL;
while(!q.empty())
{
node=q.front();
q.pop();
if(node->left!=NULL)
{
q.push(node->left);
s+=to_string(node->left->val);
}
else
{
s+="null";
}
s+=",";
if(node->right!=NULL)
{
q.push(node->right);
s+=to_string(node->right->val);
}
else
{
s+="null";
}
s+=",";
}
int len=s.size();
s[len-1]=']';
return s;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<int> vt;
queue<TreeNode*> q;
vt=split(data, ',');
TreeNode *root=NULL;
if(vt.size()>0)
{
TreeNode *node=NULL;
node=(TreeNode*)malloc(sizeof(TreeNode));
node->val=vt[0];
node->left=NULL,node->right=NULL;
root=node;
q.push(root);
}
int k=1;
while(k<vt.size())
{
TreeNode* node=q.front();
if(vt[k]==INF)
node->left=NULL;
else
{
TreeNode *lt=NULL;
lt=(TreeNode*)malloc(sizeof(TreeNode));
lt->val=vt[k];
lt->left=NULL;
lt->right=NULL;
node->left=lt;
q.push(lt);
}
k++;
if(vt[k]==INF)
node->right=NULL;
else
{
TreeNode *rt=NULL;
rt=(TreeNode*)malloc(sizeof(TreeNode));
rt->val=vt[k];
rt->left=NULL;
rt->right=NULL;
node->right=rt;
q.push(rt);
}
k++;
q.pop();
}
return root;
}
};
方法2:先序遍历
class Codec {
public:
void serialize(TreeNode* root,string &s)
{
if(root==NULL)
{
s.append("null,");
return;
}
else
{
s.append(to_string(root->val));
s.append(",");
}
serialize(root->left, s);
serialize(root->right, s);
}
void deserialize(TreeNode *&root,string &s)
{
if(s=="")
return;
string tmp="";
int pos=s.find(',');
if(pos!=string::npos)
{
tmp=s.substr(0,pos);
s=s.substr(pos+1);
}
else
{
tmp=s;
s="";
}
if(atoi(tmp.c_str())||tmp.compare("0")==0)
{
root=new TreeNode(atoi(tmp.c_str()));
deserialize(root->left, s);
deserialize(root->right,s);
}
else
root=NULL;
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string s="[";
serialize(root, s);
int len=s.size();
s[len-1]=']';
return s;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode *root=NULL;
string s="";
int len=data.size();
if(len>2)
{
len-=2;
s=data.substr(1,len);
}
deserialize(root,s);
return root;
}
};