449. Serialize and Deserialize BST

/**
 * 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 {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string s;
        serialize(root, s);
        // cout<<s;
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int pos = 0;
        return deserialize(data, INT_MIN, INT_MAX, pos);
    }
private:
    void serialize(TreeNode* root, string &s) {
        if (!root) return;
        s += to_string(root->val) + "#";
        serialize(root->left, s);
        serialize(root->right, s);
    }
    TreeNode* deserialize(string &s, int l, int r, int &pos) {  //卧槽 不用&s就会空间爆
        if (pos >= s.size()) return NULL;
        int lastpos = pos;
        int val = 0;
        while (s[pos] != '#')
            val = val * 10 + s[pos++] - '0';
        pos++;
        if (l <= val && val <= r) {
            TreeNode* root = new TreeNode(val);
            root->left = deserialize(s, l, val, pos);
            root->right = deserialize(s, val, r, pos);
            return root;
        }

        pos = lastpos;
        return NULL;
    }
};


// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

results matching ""

    No results matching ""