题目链接:https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
题目如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
//树-》数组 先序
dfs(root);
return res;
}
void dfs(TreeNode* root){
if(!root){
res+="None,";
return ;
}
res+=to_string(root->val)+",";
dfs(root->left);
dfs(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
//数组-》树 先序
deque<string> que;
string str="";
//将每个元素放到deque中
for(int i=0;i<data.size();i++){
if(data[i]==','){
que.push_back(str);
str="";
}else str.push_back(data[i]);
}
return dfs1(que);
}
TreeNode* dfs1(deque<string>& que){
if(que.front()=="None"){
que.pop_front();
return nullptr;
}
TreeNode* root=new TreeNode(stoi(que.front()));
que.pop_front();
root->left=dfs1(que);
root->right=dfs1(que);
return root;
}
private:
string res="";
TreeNode* res1=nullptr;
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));