题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
char* Serialize(TreeNode *root) {
if(root == nullptr)
return nullptr;
string str;
helpS(root,str);
char* res = new char[str.length()+1];
int i = 0;
for(; i < str.length(); ++i)
res[i] = str[i];
res[i] = '\0';
return res;
}
void helpS(TreeNode* root, string& str)
{
if(root == nullptr)
{
str +='#';
return;
}
string ch = to_string(root->val);
str += ch;
str += ',';
helpS(root->left,str);
helpS(root->right,str);
}
TreeNode* Deserialize(char *str) {
if(str == nullptr)
return nullptr;
TreeNode* res = helpD(&str);
return res;
}
TreeNode* helpD(char** str)//*str是指向字符串中str这个字符的指针,因为指针要往后移,要指向下一个字符,也就是说过程中要改变指针,所以应该传这个指针的地址,所以是二级指针
{
if(**str == '#')
{
++ (*str);
return nullptr;
}
int num = 0;
while(**str != '\0' && **str != ',')
{
num = num*10 + ((**str) - '0');
++(*str);
}
TreeNode* root = new TreeNode(num);//建立根节点
if((**str) == '\0')
return root;
else
(*str) ++;
root->left = helpD(str);
root->right = helpD(str);
return root;
}
};