题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
#include <cstring>
#include <string>
class Solution {
public:
void SerializeFun(TreeNode* root, string& str){
if (root==NULL) {
str += "#";
return;
}
str += to_string(root->val);
str += "!";
SerializeFun(root->left, str);
SerializeFun(root->right, str);
}
char* Serialize(TreeNode *root) {
string str;
SerializeFun(root, str);
char* charans = new char[str.length() + 1];
strcpy(charans, str.c_str());
charans[str.length()] = '*';
return charans;
}
TreeNode* DeserializeFun(char** str){
if (**str == '#') {
(*str)++;
return nullptr;
}
int val = 0;
while (**str != '!' && **str != '*') {
val = val * 10 + **str - '0';
(*str)++;
}
TreeNode* root = new TreeNode(val);
if (**str == '*') {
return root;
}
else {
(*str)++;
}
root->left = DeserializeFun(str);
root->right = DeserializeFun(str);
return root;
}
TreeNode* Deserialize(char *str) {
if (str == "#") {
return nullptr;
}
return DeserializeFun(&str);
}
};
回家再手敲一遍
查看12道真题和解析