这破题,可是做死我了,数组还有引用使用
前序遍历,其实思路是清晰明确的,问题出就出在string想char转换时,必须先给char数组指定长度,太气了。*strcpy(char,s.c_str());在这步操作前,必须要先对char指定长度。**
class Solution {
public:
char Serialize(TreeNode *root) {
if(!root) return NULL;
string s;
ser(root,s);
char *res = new char[s.size() + 1];
strcpy(res,s.c_str());
return res;
}
void ser(TreeNode *root,string &s){
if(!root){
s += '#';
return;
}
s += to_string(root->val);
s += '!';
ser(root->left,s);
ser(root->right,s);
return;
}
TreeNode* Deserialize(char* str) {
if(!str) return NULL;
return deser(str);
}
TreeNode* deser(char* &str){
if(*str == '#'){
str++;
return NULL;
}
int num = 0;
while(*str != '\0' && *str != '!'){
num = num*10 + *str - '0';
str++;
}
TreeNode *root = new TreeNode(num);
if(*str == '\0') return root;
str++;
root->left = deser(str);
root->right = deser(str);
return root;
}};

京公网安备 11010502036488号