spider68

Serialize and Deserialize N-ary Tree

May 24th, 2021
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 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.    
  24.     string serialize(Node* root) {
  25.         if(!root)return "#";
  26.         string str = to_string(root->val);
  27.        
  28.         for(Node* n : root->children)
  29.             str += "," + serialize(n);
  30.         str += ",#";
  31.         return str;
  32.     }
  33.    
  34.     // Decodes your encoded data to tree.
  35.     Node* deserialize(stringstream& ss) {      
  36.         string node;
  37.         getline(ss, node, ',');
  38.         if(node == "#"){
  39.             return nullptr;
  40.         }
  41.        
  42.         Node* root = new Node( stoi(node) );
  43.         Node* child = deserialize(ss);
  44.         while(child){
  45.             root->children.push_back(child);
  46.             child = deserialize(ss);
  47.         }
  48.         return root;
  49.     }
  50.     Node* deserialize(string data) {
  51.         stringstream ss(data);
  52.         return deserialize(ss);
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment