Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- /*
- Logic:
- step1: We will traverse the tree levelwise using BFS in serialize function and store in string.
- while stroing tree in string,we will give one space between every node and "null" for NULL node.
- step2: In deserialize function,we will store the nodes into vector of string and pass to fun.
- fun will traverse the tree levelwise using BFS and push the elements into tree.
- */
- class Codec {
- public:
- string serialize(TreeNode* root) {
- if(!root) return "";
- deque<TreeNode*> q;
- q.push_back(root);
- string res="";
- while(!q.empty()){
- int k=q.size();
- for(int i=0;i<k;i++){
- TreeNode* temp=q.front();
- q.pop_front();
- if(!temp){
- res+="null ";
- }
- else{
- res+=to_string(temp->val);
- res+=" ";
- q.push_back(temp->left);
- q.push_back(temp->right);
- }
- }
- }
- return res;
- }
- int _stoi(string s){
- int ans=0,i=0;
- bool sign=false;
- if(s[i]=='-'){ sign=true;i++;}
- while(i<s.size()){
- ans=ans*10+(s[i++]-'0');
- }
- if(sign) ans=-ans;
- return ans;
- }
- TreeNode* fun(vector <string> arr){
- if(arr.size()==0) return NULL;
- deque<TreeNode*> q;
- TreeNode* res=new TreeNode(_stoi(arr[0]));
- q.push_back(res);
- int i=1;
- while(!q.empty()){
- int k=q.size();
- for(int j=0;j<k;j++){
- TreeNode* temp=q.front();
- q.pop_front();
- if(arr[i]!="null"){
- temp->left=new TreeNode(_stoi(arr[i++]));
- q.push_back(temp->left);
- }
- else i++;
- if(arr[i]!="null"){
- temp->right=new TreeNode(_stoi(arr[i++]));
- q.push_back(temp->right);
- }
- else i++;
- }
- }
- return res;
- }
- TreeNode* deserialize(string s) {
- if(s=="") return NULL;
- vector <string> arr;
- int i=0;
- while(i<s.size()){
- if(s[i]=='n'){ arr.push_back("null"); i+=5;}
- else if(s[i]=='-' || isdigit(s[i])){ //number can be negative also
- bool sign=false;
- if(s[i]=='-'){ sign=true;i++;}
- string val="";
- while(isdigit(s[i])){
- val+=s[i++];
- }
- if(sign) val="-"+val;
- arr.push_back(val);
- i++;
- }
- }
- return fun(arr);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement