题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
思路
//用递归
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* decode(char *&str) {
if(*str == '#'){
str++;
return NULL;
}
int num = 0;
while(*str != ',')
num = num*10 +(*(str++)-'0');//取出一个节点的数字
str++;//删除一个字符','
TreeNode *root = new TreeNode(num);//算出节点总数量
root->left = decode(str);
root->right = decode(str);
return root;
}
char* Serialize(TreeNode *root) {
if(root == NULL) 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) {
return decode(str);
}
};