AcWing 50. 序列化二叉树
原题链接
困难
作者:
Charon.
,
2020-05-02 16:20:46
,
所有人可见
,
阅读 825
C++ 代码
class Solution {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string str;
dfs_s(root, str);
return str;
}
void dfs_s(TreeNode* root, string &str){
if(root == nullptr) {
str += "# ";
return;
}
str += to_string(root->val) + ' ';
dfs_s(root->left, str);
dfs_s(root->right, str);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
TreeNode* root = nullptr;
int i = 0;
dfs1(root, data, i);
return root;
}
string temp;//用这个进行转换
void dfs1(TreeNode*& root, string& str, int& i){
if(str[i] == '#'){
i += 2;
return;
}
if(i >= str.size()) return;
int k = i;
while(k < str.size() && str[k] != ' ') ++k;
for(int j = i; j < k; ++j) temp += str[j];
//直接用库函数的atoi就不用自己实现了判断正负什么的
root = new TreeNode(atoi(temp.c_str()));
temp.clear();
i = k + 1;
dfs1(root->left, str, i);
dfs1(root->right, str, i);
}
};