要求:rt
思路:
法一:bfs,出队时如果是空的就加null,非空的加值还要入队左右孩子。反序列化时入队,遍历字符串挂上去,不是null再入队
/**
* 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) {
if(!root)return "[]";
queue<TreeNode*> q;
string s="[";
bool first=true;
q.push(root);
while(!q.empty()){
TreeNode* tmp=q.front();
q.pop();
if(!first)s+=',';
first=false;
if(!tmp)s+="null";
else {
s+=to_string(tmp->val);
q.push(tmp->left);
q.push(tmp->right);
}
}
s+="]";
return s;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size()==2)return nullptr;
vector<string> v;
for(int l=1,r=2;l<data.length()&&r<data.length();){
while(data[r]!=','&&data[r]!=']')++r;
v.push_back(data.substr(l,r-l));
l=++r;
}
queue<TreeNode*> q;
TreeNode* root=new TreeNode(stoi(v[0]));
q.push(root);
int i=1;
while(!q.empty()){
TreeNode* tmp=q.front();
q.pop();
if(v[i]!="null"){
tmp->left=new TreeNode(stoi(v[i]));
q.push(tmp->left);
}
++i;
if(v[i]!="null"){
tmp->right=new TreeNode(stoi(v[i]));
q.push(tmp->right);
}
++i;
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
法二:前序遍历,要注意用vector删除会超时只能用队列
/**
* 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) {
if(!root)return "";
string s="";
dfs1(root,s);
return s;
}
void dfs1(TreeNode* root,string& s){
if(!root)s+="null,";
else{
s+=to_string(root->val)+",";
dfs1(root->left,s);
dfs1(root->right,s);
}
}
//Decodes your encoded data to tree.
queue<string> v;
TreeNode* deserialize(string data) {
if(data=="")return nullptr;
for(int l=0,r=0;l<data.length()&&r<data.length();){
while(data[r]!=',')++r;
v.push(data.substr(l,r-l));
l=++r;
}
TreeNode* root=dfs2();
return root;
}
TreeNode* dfs2(){
if(v.front()=="null"){
v.pop();
return nullptr;
}
TreeNode* root=new TreeNode(stoi(v.front()));
v.pop();
root->left=dfs2();
root->right=dfs2();
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));