Advertisement
knakul853

Untitled

Jul 24th, 2020
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. /**
  2. knakul853
  3.  */
  4. class Codec {
  5. public:
  6.  
  7.     // Encodes a tree to a single string.
  8.     string serialize(TreeNode* root) {
  9.        
  10.         ostringstream out;
  11.        
  12.         serialize( root, out );
  13.         return out.str();
  14.        
  15.     }
  16.  
  17.     // Decodes your encoded data to tree.
  18.     TreeNode* deserialize(string data) {
  19.        
  20.         istringstream in( data );
  21.        
  22.         return deserialize( in );
  23.        
  24.     }
  25.    
  26.     private:
  27.    
  28.    void serialize( TreeNode* root, ostringstream& out)
  29.    {
  30.        if( !root ){
  31.            out << "# ";
  32.        }
  33.        else
  34.        {
  35.            out << root->val << " ";
  36.            serialize( root-> left, out);
  37.            serialize( root->right, out);
  38.        }
  39.    }
  40.    
  41.     TreeNode* deserialize( istringstream& in )
  42.     {
  43.         string s;
  44.         in >> s;
  45.         if ( s == "#")
  46.             return NULL;
  47.         TreeNode* root = new TreeNode( stoi(s));
  48.        
  49.         root->left = deserialize( in );
  50.         root->right = deserialize( in );
  51.        
  52.         return root;
  53.     }
  54. };
  55.  
  56. // Your Codec object will be instantiated and called as such:
  57. // Codec codec;
  58. // codec.deserialize(codec.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement