Advertisement
nikunjsoni

428

May 7th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. /*
  2. // Definition for a Node.
  3. class Node {
  4. public:
  5.     int val;
  6.     vector<Node*> children;
  7.  
  8.     Node() {}
  9.  
  10.     Node(int _val) {
  11.         val = _val;
  12.     }
  13.  
  14.     Node(int _val, vector<Node*> _children) {
  15.         val = _val;
  16.         children = _children;
  17.     }
  18. };
  19. */
  20.  
  21. class Codec {
  22. public:
  23.     // Encodes a tree to a single string.
  24.     string serialize(Node* root) {
  25.         // If tree is null.
  26.         if(!root) return "#";
  27.        
  28.         // Add current node's value and then it's length.
  29.         string repr = "";
  30.         repr += to_string(root->val)+',';
  31.         repr += to_string((root->children).size())+',';
  32.        
  33.         // Add each child's representation.
  34.         for(int i=0; i<(root->children).size(); i++)
  35.             repr += serialize((root->children)[i]);
  36.         return repr;
  37.     }
  38.    
  39.     // Decodes your encoded data to tree.
  40.     Node* deserialize(string data) {
  41.         return dserialize(data);
  42.     }
  43.    
  44.     Node* dserialize(string &data){
  45.         // If tree is null.
  46.         if(data[0] == '#') return NULL;
  47.        
  48.         // Create node with value.
  49.         int pos = data.find(',');
  50.         int val = stoi(data.substr(0, pos));
  51.         data = data.substr(pos+1);
  52.         Node *node = new Node(val);
  53.        
  54.         // Find number of children and recurse over each.
  55.         pos = data.find(',');
  56.         int numChild = stoi(data.substr(0, pos));
  57.         data = data.substr(pos+1);
  58.         for(int i=0; i<numChild; i++)
  59.             (node->children).push_back(dserialize(data));
  60.         return node;
  61.     }
  62. };
  63.  
  64. // Your Codec object will be instantiated and called as such:
  65. // Codec codec;
  66. // codec.deserialize(codec.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement