Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- class Codec {
- private:
- static const int BITS = 12;
- public:
- // Encodes a tree to a single string.
- string serialize(TreeNode* root) {
- if (root == nullptr) return string(BITS - 1, '0') + "1";
- string bin = to_binary(root->val);
- bin += serialize(root->left);
- bin += serialize(root->right);
- return bin;
- }
- // Decodes your encoded data to tree.
- TreeNode *deserialize(string data) {
- int idx = 0;
- return deserialize(data, idx);
- }
- private:
- TreeNode* deserialize(string &data, int &idx) {
- string bin = data.substr(idx, BITS);
- if (bin == string(BITS - 1, '0') + "1") return nullptr;
- TreeNode *root = new TreeNode(from_binary(bin));
- idx += BITS;
- root->left = deserialize(data, idx);
- idx += BITS;
- root->right = deserialize(data, idx);
- return root;
- }
- string to_binary(int n) {
- bool neg = n < 0;
- n = abs(n);
- string bin = "";
- while (n) {
- int bit = n & 1;
- bin += (char) ('0' + bit);
- n >>= 1;
- }
- while ((int) bin.size() < BITS - 1) {
- bin += '0';
- }
- bin += neg ? '1' : '0';
- return bin;
- }
- int from_binary(string &bin) {
- int val = 0;
- for (int i = 0; i < BITS - 1; i++) {
- if (bin[i] == '1') {
- val |= (1 << i);
- }
- }
- if (bin[BITS - 1] == '1') val = -val;
- return val;
- }
- };
- // Your Codec object will be instantiated and called as such:
- // Codec ser, deser;
- // TreeNode* ans = deser.deserialize(ser.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement