Advertisement
leoanjos

Serialize and Deserialize Binary Tree

Jun 11th, 2022
1,203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 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. class Codec {
  11. private:
  12.     static const int BITS = 12;
  13.  
  14. public:
  15.     // Encodes a tree to a single string.
  16.     string serialize(TreeNode* root) {
  17.         if (root == nullptr) return string(BITS - 1, '0') + "1";
  18.        
  19.         string bin = to_binary(root->val);
  20.         bin += serialize(root->left);
  21.         bin += serialize(root->right);
  22.        
  23.         return bin;
  24.     }
  25.  
  26.     // Decodes your encoded data to tree.
  27.     TreeNode *deserialize(string data) {
  28.         int idx = 0;
  29.         return deserialize(data, idx);
  30.     }
  31.    
  32. private:
  33.     TreeNode* deserialize(string &data, int &idx) {
  34.         string bin = data.substr(idx, BITS);
  35.         if (bin == string(BITS - 1, '0') + "1") return nullptr;
  36.        
  37.         TreeNode *root = new TreeNode(from_binary(bin));
  38.        
  39.         idx += BITS;
  40.         root->left = deserialize(data, idx);
  41.        
  42.         idx += BITS;
  43.         root->right = deserialize(data, idx);
  44.        
  45.         return root;
  46.     }
  47.  
  48.     string to_binary(int n) {
  49.         bool neg = n < 0;
  50.         n = abs(n);
  51.        
  52.         string bin = "";
  53.         while (n) {
  54.             int bit = n & 1;
  55.             bin += (char) ('0' + bit);
  56.             n >>= 1;
  57.         }
  58.        
  59.         while ((int) bin.size() < BITS - 1) {
  60.             bin += '0';
  61.         }
  62.        
  63.         bin += neg ? '1' : '0';
  64.        
  65.         return bin;
  66.     }
  67.    
  68.     int from_binary(string &bin) {
  69.         int val = 0;
  70.         for (int i = 0; i < BITS - 1; i++) {
  71.             if (bin[i] == '1') {
  72.                 val |= (1 << i);
  73.             }
  74.         }
  75.        
  76.         if (bin[BITS - 1] == '1') val = -val;
  77.         return val;
  78.     }
  79. };
  80.  
  81. // Your Codec object will be instantiated and called as such:
  82. // Codec ser, deser;
  83. // TreeNode* ans = deser.deserialize(ser.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement