艾恩凝
个人博客 https://aeneag.xyz/
公众号 技术乱舞
这个题不算困难
题目
https://leetcode-cn.com/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) {
if(!root)return "None";
return to_string(root->val)+","+ serialize(root->left)+","+serialize(root->right);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
list<string> array;
string tmp;
for(auto& ch :data){
if(ch != ','){
tmp.push_back(ch);
}else{
array.push_back(tmp);
tmp.clear();
}
}
array.push_back(tmp);
return dfs(array);
}
TreeNode* dfs(list<string>& array){
if(array.front() == "None"){
array.erase(array.begin());
return nullptr;
}
TreeNode* root = new TreeNode(stoi(array.front()));
array.erase(array.begin());
root->left = dfs(array);
root->right = dfs(array);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
欢迎关注 #公众号:技术乱舞 一起交流
灵魂碰撞