问题描述
解决思路
采用先序的顺序,递归序列化和反序列化建树
核心代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
#include <exception>
#include <string>
class Solution {
public:
void SeFuction(TreeNode *root,string &s){
if(!root){
s+='#';
return;
}
string temp=to_string(root->val);
s+=temp+'!';
SeFuction(root->left,s);
SeFuction(root->right,s);
}
char* Serialize(TreeNode *root) {
string s;
SeFuction(root, s);
char *res=new char[s.length()+1];
strcpy(res,s.c_str());
res[s.length()]='\0';
return res;
}
TreeNode* DeFunction(char **s){//想在函数中修改一级指针的值,故采用二级指针
if(**s=='#'){
(*s)++;
return nullptr;
}
int val=0;
while(**s!='!'&&**s!='\0'){
val=val*10+(**s-'0');
(*s)++;
}
auto* cur=new TreeNode(val);
(*s)++;
if(**s=='\0') return cur;
cur->left=DeFunction(s);
cur->right=DeFunction(s);
return cur;
}
TreeNode* Deserialize(char *str) {
//cout<<str;
return DeFunction(&str);
}
};