nikunjsoni

449

Jul 10th, 2021
96
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. class Codec {
  11. public:
  12.  
  13.     // Encodes a tree to a single string.
  14.     string serialize(TreeNode* root) {
  15.         if(!root) return "#";
  16.         return to_string(root->val)+","+serialize(root->left)+","+serialize(root->right);
  17.     }
  18.  
  19.     // Decodes your encoded data to tree.
  20.     TreeNode* deserialize(string data) {
  21.         int idx = 0;
  22.         return dserialize(data, idx);
  23.     }
  24.    
  25.     TreeNode* dserialize(string &data, int &idx){
  26.         if(data[idx] == '#'){
  27.             if(data.length()-idx > 1)
  28.                 idx += 2;
  29.             return NULL;
  30.         }
  31.         int val = 0;
  32.         while(idx < data.length() && isdigit(data[idx])){
  33.             val = val*10+data[idx]-'0';
  34.             idx++;
  35.         }
  36.         if(idx<data.length()-1) idx++;
  37.         TreeNode* node = new TreeNode(val);
  38.         node->left = dserialize(data, idx);
  39.         node->right = dserialize(data, idx);
  40.         return node;
  41.     }
  42.    
  43. };
  44.  
  45. // Your Codec object will be instantiated and called as such:
  46. // Codec* ser = new Codec();
  47. // Codec* deser = new Codec();
  48. // string tree = ser->serialize(root);
  49. // TreeNode* ans = deser->deserialize(tree);
  50. // return ans;
RAW Paste Data