Created
June 14, 2017 19:33
-
-
Save devanshdalal/2921eeb8bb77cfa553188dfd45cc19f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or | |
transmitted across a network connection link to be reconstructed later in the same or another computer environment. | |
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization | |
algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. | |
For example, you may serialize the following tree | |
1 | |
/ \ | |
2 -3 | |
/ | |
1 | |
inorder: [2] 1 [[1] -3] : (2 1 1 -3) | |
pre-order: 1 [2] [-3 1] : (1 2 -3 1) | |
recover | |
inorder: (2 1 1 -3) | |
pre-order: (1 2 -3 1) | |
1[2[][]][-3[1][]] | |
*/ | |
#include <bits/stdc++.h> | |
using namespace std; | |
struct node{ | |
int val; | |
node* left; | |
node* right; | |
node(int v): | |
val(v) | |
{ | |
left = nullptr; | |
right = nullptr; | |
} | |
}; | |
std::string serialize(node * root){ | |
if(root==nullptr){ | |
return ""; | |
} | |
auto l = serialize(root->left); | |
auto r = serialize(root->right); | |
return std::to_string(root->val)+"["+l+"]["+r+"]"; | |
} | |
node* deserialize(const std::string& s){ | |
if(s.length()<1)return nullptr; | |
//std::cerr << s << "\n"; | |
std::size_t first = s.find("["); | |
int opens=1; | |
int i; | |
for(i=first+1;i<s.length();i++){ | |
if(s[i]=='['){ | |
opens++; | |
}else if(s[i]==']'){ | |
opens--; | |
} | |
if(opens==0)break; | |
} | |
//std::cerr << i << " " << first << "\n"; | |
auto left = deserialize(i==first+1?"":s.substr(first+1,i - first-1)); | |
//std::cerr << i << " " << first << "\n"; | |
i+=2; | |
int second = i; | |
opens=1; | |
for(;i<s.length();i++){ | |
if(s[i]=='['){ | |
opens++; | |
}else if(s[i]==']'){ | |
opens--; | |
} | |
if(opens==0)break; | |
} | |
auto right = deserialize(second==i?"":s.substr(second,i - second)); | |
node * root = new node(std::stoi(s.substr(0,first))); | |
root->left = left; | |
root->right = right; | |
return root; | |
} | |
int main(){ | |
node * r = new node(1); | |
r->left = new node(2); | |
r->right = new node(-3); | |
r->right->left = new node(1); | |
std::string st = serialize(r); | |
std::cerr << st << "\n"; | |
auto recover = deserialize(st); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment