Advertisement
Kali_prasad

serialize and deserialize

Jan 7th, 2023
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10.  
  11.  
  12. std::vector<std::string> split(const std::string& str, char delim) {
  13.   std::vector<std::string> tokens;
  14.   size_t start = 0;
  15.   size_t end = 0;
  16.   while ((end = str.find(delim, start)) != std::string::npos) {
  17.     tokens.push_back(str.substr(start, end - start));
  18.     start = end + 1;
  19.   }
  20.   tokens.push_back(str.substr(start));
  21.   return tokens;
  22. }
  23. class Codec {
  24. public:
  25.     int ind;
  26.     // Encodes a tree to a single string.
  27.     string serialize(TreeNode* root) {
  28.         if(!root) return "N";
  29.         return
  30.             to_string(root->val)+","+serialize(root->left)+","
  31.             +serialize(root->right);
  32.     }
  33.     TreeNode* construct(vector<string> data){
  34.         string res=data[ind];
  35.         if(data[ind]=="N") {
  36.             ind+=1;
  37.             return NULL;
  38.  
  39.         }
  40.         int val=stoi(res);
  41.         ind+=1;//index has to be incremented only after it is accessed
  42.         TreeNode* curr=new TreeNode(val);
  43.         curr->left=construct(data);
  44.         curr->right=construct(data);
  45.         return curr;
  46.  
  47.     }
  48.     // Decodes your encoded data to tree.
  49.     TreeNode* deserialize(string data) {
  50.         ind=0;
  51.         vector<string> arr=split(data,',');
  52.         return construct(arr);
  53.         return NULL;
  54.     }
  55. };
  56.  
  57. // Your Codec object will be instantiated and called as such:
  58. // Codec ser, deser;
  59. // TreeNode* ans = deser.deserialize(ser.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement