class Solution {
public:
char* Serialize(TreeNode *root) {
string s;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* tmp = q.front();
q.pop();
if(tmp){
s += to_string(tmp->val);
s += ",";// s.push_back(',');可以将char 复制转化为string
}else{
s += "#,";
continue;
}
q.push(tmp->left);
q.push(tmp->right);
}
char *ret = new char[s.length() + 1]; // 多一位存放‘\0’
strcpy(ret, s.c_str());// c_str() string 转化为char
return ret;
}
TreeNode* Deserialize(char *str) {
if(str == nullptr) {
return nullptr;
}
string s(str);
if(str[0] == '#'){
return nullptr;
}
queue<TreeNode*> nodes;
TreeNode *ret = new TreeNode(atoi(s.c_str())); // atoi()char* 转化为 int
s = s.substr(s.find_first_of(',') + 1);
nodes.push(ret);
while(!nodes.empty() && !s.empty()){
TreeNode *node = nodes.front();
nodes.pop();
if(s[0] == '#'){
node->left = nullptr;
s = s.substr(2);//从第二个位置得到子串 '#,'不要
}
else {
node->left = new TreeNode(atoi(s.c_str()));
nodes.push(node->left);
s = s.substr(s.find_first_of(',') + 1);// 找到到第一个, find一样
}
if(s[0] == '#'){
node->right = nullptr;
s = s.substr(2);
}
else {
node->right = new TreeNode(atoi(s.c_str()));
nodes.push(node->right);
s = s.substr(s.find_first_of(',') + 1);
}
}
return ret;
}
};