题解 | 序列化二叉树
序列化二叉树
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 <string>
class Solution {
public:
void dfs(TreeNode* root,string& str)
{
if(root == nullptr)
{
str+="#,";
return;
}
str += to_string(root->val)+",";
dfs(root->left,str);
dfs(root->right,str);
}
string str;
char* Serialize(TreeNode *root) {
str.clear();
dfs(root,str);
cout<<str<<endl;
return str.data();
}
TreeNode* redfs(string& str,int& idx)
{
if(idx>=str.size()) return nullptr;
if(str[idx]=='#')
{
idx++;
return nullptr;
}
int sum = 0;
for(;str[idx]!=',';idx++)
{
sum = sum * 10 + str[idx] - '0';
}
TreeNode* root = new TreeNode(sum);
root->left = redfs(str, ++idx);
root->right = redfs(str, ++idx);
return root;
}
TreeNode* Deserialize(char *str) {
string msg(str);
int idx = 0;
return redfs(msg,idx);
}
};
查看58道真题和解析