class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root==nullptr) return nullptr; //返回nullptr,返回NULL,应改为返回""
queue<TreeNode*> qu;
qu.push(root);
string res;
while(!qu.empty()){
TreeNode* front=qu.front();
if(front){
res+=to_string((long long)front->val);
res+=",";
qu.push(front->left);
qu.push(front->right);
}else{
res+="#";
res+=",";
}
qu.pop();
}
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return nullptr;
vector<int> in;
int first=0;
int second=0;
while(second<data.size()){
while(data[second]!=','&&second!=data.size()){ 应该先判断second是否越界
second++;
}
if(data[first]=='#'){
in.push_back(NULL); //有可能节点的值就为0
}else{
in.push_back(atoi(data.substr(first,second-first).data()));
}
first=++second;
}
int i=0;
TreeNode* root=new TreeNode(in[i]);
queue<TreeNode*> qu;
qu.push(root);
while(2*i+2<in.size()){
TreeNode* front=qu.front();
if(in[2*i+1]!=NULL) {
front->left=new TreeNode(in[2*i+1]);
qu.push(front->left);
}
if(in[2*i+2]!=NULL) {
front->right=new TreeNode(in[2*i+2]);
qu.push(front->right);
}
i++;
qu.pop();
}
return root;
}
};
改后:
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(root==nullptr) return "";
queue<TreeNode*> qu;
qu.push(root);
string res;
while(!qu.empty()){
TreeNode* front=qu.front();
if(front){
res+=to_string((long long)front->val);
res+=",";
qu.push(front->left);
qu.push(front->right);
}else{
res+="#";
res+=",";
}
qu.pop();
}
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return nullptr;
vector<int> in;
int first=0;
int second=0;
while(second<data.size()){
while(second!=data.size()&&data[second]!=','){ 应该先判断second是否越界
second++;
}
if(data[first]=='#'){
in.push_back(0x7fffffff);
}else{
in.push_back(atoi(data.substr(first,second-first).data()));
}
first=++second;
}
int i=0;
TreeNode* root=new TreeNode(in[i]);
queue<TreeNode*> qu;
qu.push(root);
while(2*i+2<in.size()){
TreeNode* front=qu.front();
if(in[2*i+1]!=0x7fffffff) {
front->left=new TreeNode(in[2*i+1]);
qu.push(front->left);
}
if(in[2*i+2]!=0x7fffffff) {
front->right=new TreeNode(in[2*i+2]);
qu.push(front->right);
}
i++;
qu.pop();
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
如果是一般的树会怎么样呢 ?
定义一个数据结构来保存每个节点的孩子数,反序列化轮到这个节点时通对这个节点前面所有节点的孩子数求和决定这个节点应该选取那个数值作为自己的孩子节点