/*
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) {
//选择一种遍历方式,将这些结点转化为字符
char* ch = nullptr;
if(root == nullptr) return ch;
string str = "";
SerializeCore(root, str);
ch = new char[str.length()+1];
int i;
for(i = 0; i < str.length(); ++i){
ch[i] = str[i];
}
ch[i] = '\0';
return ch;
}
void SerializeCore(TreeNode* root, string &str){
if(root == nullptr){
str += '#';
return;
}
str += to_string(root->val);
str += ',';
SerializeCore(root->left, str);
SerializeCore(root->right, str);
}
TreeNode* Deserialize(char *str) {
//用字符串来建树
TreeNode* root = nullptr;
if(str == nullptr) return root;
DeserializeCore(root, str);
return root;
}
void DeserializeCore(TreeNode*&root, char *&str){
if(*str == '\0') return;
if(*str == '#'){
root = nullptr;
++str;
return;
}
int num = 0;
while(*str != '\0' && *str != ','){
num = num * 10 + (*str - '0');
++str;
}
if(*str != '\0') ++str;
root = new TreeNode(num);
DeserializeCore(root->left,str);
DeserializeCore(root->right, str);
}
};
剑指offer——序列化二叉树C++
最新推荐文章于 2021-08-01 22:25:32 发布