/**
* 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 res="[";
queue<TreeNode*> q;
q.push(root);
res+=myitos(root->val);
res+=',';
while(!q.empty()){
root = q.front();
q.pop();
if(root->left){
res+=myitos(root->left->val);
q.push(root->left);
}else
res+="null";
res+=',';
if(root->right){
res+=myitos(root->right->val);
q.push(root->right);
}else
res+="null";
res+=',';
}
int i=res.size()-1;
for(;i>=0;i--){
if(isdigit(res[i]))
break;
}
res=res.substr(0,i+1);
res+=']';
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size()==2) return NULL;
queue<TreeNode*> q;
queue<TreeNode*> cur;
for(int i=1;i<data.size()-1;){
for(int j=i;j<data.size();j++){
if(data[j]==',' || data[j]==']'){
TreeNode *temp=NULL;
if(isdigit(data[i])) {
int sum=0;
for(int k=i;k<=j-1;k++){
sum = sum*10+(data[k]-48);
}
temp = new TreeNode(sum);
}
if(data[i]=='-') {
int sum=0;
for(int k=i+1;k<=j-1;k++){
sum = sum*10+(data[k]-48);
}
temp = new TreeNode(-sum);
}
q.push(temp);
i=j+1;
break;
}
}
}
cur.push(q.front());q.pop();
TreeNode *root=cur.front();
while(!cur.empty()){
if(q.empty()) return root;
TreeNode *temp=cur.front();cur.pop();
TreeNode *l =q.front();q.pop();
TreeNode *r=NULL;
if(!q.empty()) {
r=q.front();
q.pop();
}
temp->left =l;
temp->right=r;
if(l)
cur.push(l);
if(r)
cur.push(r);
}
return root;
}
string myitos(int temp){
string t="";
if(temp<0){
t+='-';
temp=-temp;
}
string i="";
do{
i+=temp%10 + 48;
temp/=10;
}while(temp);
reverse(i.begin(),i.end());
t+=i;
return t;
}
};
//能写的这么长也算是前无古人后无来者了吧,,,,纪念下首次超100行的leetcode代码。。。。。
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));```
二叉树序列化和反序列化(bfs),和leetcode一致
最新推荐文章于 2025-05-14 22:27:35 发布