题目:请实现两个函数,分别用来序列化和反序列化二叉树。这里没有规定序列化的方式。
class Solution {
public:
char* Serialize(TreeNode *root) {
if(!root) return "$";
string r = to_string(root->val);
r.push_back(',');
char *left = Serialize(root->left);
char *right = Serialize(root->right);
char *ret = new char[strlen(left) + strlen(right) + r.size()];
strcpy(ret, r.c_str());
strcat(ret, left);
strcat(ret, right);
return ret;
}
TreeNode* Deserialize(char *str) {
if(str == NULL)
return NULL;
return decode(str);
}
TreeNode* decode(char *&str) //注意传递str的引用
{
if(*str == '$')
{
str++;
return NULL;
}
int num=0;
while(*str != ',')
{
num = 10* num + (*(str++)-'0');
}
str++;
TreeNode* node = new TreeNode(num);
node->left = decode(str);
node->right = decode(str);
return node;
}
};