[leetcode]449. Serialize and Deserialize BST

[leetcode]449. Serialize and Deserialize BST


Analysis

唉 感觉应该GG了,还是好好刷题看论文吧—— [每天刷题并不难0.0]

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

二叉树的解码和编码,解码的话就是用preOrder把所有节点值保存起来,编码的话就是反过来

Implement

/**
 * 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 tree = "";
        preOrder(tree, root);
        return tree;
    }
    void preOrder(string& tree, TreeNode* node){
        if(node == NULL)
            return ;
        tree += to_string(node->val)+",";
        preOrder(tree, node->left);
        preOrder(tree, node->right);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if(data == "")
            return NULL;
        vector<string> val1;
        string tmp = "";
        for(int i=0; i<data.size(); i++){
            if(data[i] == ','){
                val1.push_back(tmp);
                tmp = "";
            }
            else
                tmp += data[i];
        }
        queue<int> q_val;
        for(string v:val1)
            q_val.push(stoi(v));
        return build(q_val, INT_MIN, INT_MAX);
    }
    TreeNode* build(queue<int>& q, int low, int up){
        if(q.empty())
            return NULL;
        int vv = q.front();
        if(vv < low || vv > up)
            return NULL;
        q.pop();
        TreeNode* root = new TreeNode(vv);
        root->left = build(q, low, vv);
        root->right = build(q, vv, up);
        return root;
    }
};

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/84785881