
不知道为什么在leetcode上会栈溢出,在vs上跑都是好的。
序列化:树→字符串数组→字符串
反序列化:字符串→字符串数组→树
字符串的格式为"1,2,3,#,#,4,5;"
/**
* 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 "";
string str;
vector<string> vec;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
TreeNode* cur = que.front();
que.pop();
if(!cur){
vec.push_back("#");
continue;
}else{
vec.push_back(to_string(cur->val));
que.push(cur->left);
que.push(cur->right);
}
}
while(vec.back()=="#")
vec.pop_back();
for(int i=0;i<vec.size();++i){
if(i==vec.size()-1)
str += vec[i] + ";";
else
str += vec[i] + ",";
}
return str;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return nullptr;
int n = data.size();
vector<string> vec;
int i=0;
while(i<n-1){
string str;
while(data[i]!=';' || data[i]!=',')
str+=data[i++];
vec.push_back(str);
++i;
}
int index = 0;
int m = vec.size();
TreeNode* root = new TreeNode(stoi(vec[index]));
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
TreeNode* cur = que.front();
que.pop();
if(!cur) continue;
int leftIndex = 2*index+1;
if(leftIndex<m && vec[leftIndex]!="#")
cur->left = new TreeNode(stoi(vec[leftIndex]));
else
cur->left = nullptr;
int rightIndex = leftIndex+1;
if((leftIndex)<m && vec[leftIndex]!="#")
cur->right = new TreeNode(stoi(vec[leftIndex]));
else
cur->right = nullptr;
que.push(cur->left);
que.push(cur->right);
++index;
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
本文介绍了一种二叉树的序列化和反序列化方法,使用队列遍历将二叉树转化为字符串,并能从字符串还原成原来的二叉树结构。通过具体的C++实现代码,展示了如何进行序列化和反序列化的操作。
946

被折叠的 条评论
为什么被折叠?



