DFS谁用谁说好!这用DFS也太方便了,直接套前序遍历就可以了!当然字符流也功不可没,因为分割字符串也变得简单!
序列化居然只需要三行代码!反序列化的时候,有个问题,我没有解决,就是当字符流ss用完之后呢?这时候会怎么样?不明白……
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root)
return "null ";
return to_string(root->val)+" "+serialize(root->left)+serialize(root->right);
}
TreeNode *helptrans(istringstream& ss)
{
string s;
TreeNode *root=NULL;
ss>>s;
if(s=="null")
return root;
root=new TreeNode(stoi(s));
root->left=helptrans(ss);
root->right=helptrans(ss);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream ss(data);
return helptrans(ss);
}
};
用后序也做了一遍,但是后面几个结点比较多的会超时,其实也没什么;这个暂时解决不了
主要有两点
1:序列化用后序遍历,反序列化要从最后向前,先right后left
2:如果是把字符串倒过来的话,比较麻烦,要注意补上空格
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if(!root)
return "null ";
return serialize(root->left)+serialize(root->right)+to_string(root->val)+" ";
}
TreeNode *helptrans(istringstream& ss)
{
string s;
TreeNode *root=NULL;
ss>>s;
if(s=="null")
return root;
root=new TreeNode(stoi(s));
root->right=helptrans(ss);
root->left=helptrans(ss);
return root;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
stringstream ss;
ss<<data;
string s,trans;
while(ss>>s)
trans=s+" "+trans;
istringstream st(trans);
return helptrans(st);
}
};