注意数字是负数的情况,y神视频中似乎没提到
```
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) { //用前序序列化
string res;
dfs_s(root, res);
return res;
}
void dfs_s(TreeNode* root, string& s){
if(!root){
s += "null ";
return;
}
s += to_string(root->val) + ' ';
dfs_s(root->left, s);
dfs_s(root->right, s);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) { //反序列化
int u = 0;
return dfs_d(data, u);
}
TreeNode* dfs_d(string data, int &u){
if(u == data.size()) return NULL;
int k = u;
while(data[k] != ' ') k++;
if(data[u] == 'n'){
u = k + 1;
return NULL;
}
int val = 0, flag = 0;
for(int i = u; i < k; i++){
if(data[i] == '-') { //做个标记
flag = 1;
continue;
}
val = val * 10 + data[i] - '0';
}
u = k + 1;
if(flag) val = -val; //标记使用
auto root = new TreeNode(val);
root->left = dfs_d(data, u);
root->right = dfs_d(data, u);
return root;
}
};
```