[LC] serialization and deserialization of binary tree

subject

Serialization is the operation of converting a data structure or object into continuous bits, and then the converted data can be stored in a file or memory. At the same time, it can also be transmitted to another computer environment through the network, and the original data can be reconstructed in the opposite way.

Please design an algorithm to realize the serialization and deserialization of binary tree. There is no restriction on the execution logic of your sequence / deserialization algorithm. You only need to ensure that a binary tree can be serialized into a string and deserialize the string into the original tree structure.

Note: the input / output format is the same as that currently used by LeetCode. For details, please refer to the format of LeetCode serialized binary tree. You don't have to take this approach, you can also take other methods to solve the problem.

Example

pattern

/**
 * 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) {
        
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));

Problem solution

Depth first

First, the official depth priority
The essence of serialization is to encode its value, and what is important is to encode the structure
You can traverse the tree to accomplish the above tasks. As we all know, we generally have two strategies: breadth first search and depth first search.

Breadth first search can traverse all nodes from top to bottom in hierarchical order
Depth first search can start from a root, extend to a leaf, and then return to the root to another branch. According to the relative order among the root node, left node and right node, the depth first search strategy can be further divided into:

  • Preorder traversal
  • Medium order traversal
  • Postorder traversal
class Codec {
public:
    void rserialize(TreeNode* root,string& str)
    {
        if(!root) str+="None,";
        else{
            str+=to_string(root->val) + ","; //Convert value to character
            rserialize(root->left,str); //Serialize left
            rserialize(root->right,str);  //Serialize right
        }
    }

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string ret; //Because you want to declare a common, you need to increase or decrease the value on it every time, so you can write another function to pass the address and recurse with the new function, or you can use this (see writing method 2 below)
        rserialize(root,ret);
        return ret;
    }
    /*
    string serialize(TreeNode* root) {
        string ret;
        if(!root) return "None,";
        ret += to_string(root->val)+",";
        ret+=serialize(root->left);
        ret+=serialize(root->right);
        return ret;
    }
    */


    TreeNode* rdeserialize(list<string>& dataArray)
    {
        if(dataArray.front() == "None"){
            dataArray.erase(dataArray.begin());
            return nullptr;
        }
        TreeNode* root = new TreeNode(stoi(dataArray.front()));
        dataArray.erase(dataArray.begin());
        root->left = rdeserialize(dataArray);
        root->right = rdeserialize(dataArray);
        return root;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        list<string> dataArray;  //It is newly learned that list is a two-way linked list encapsulated by stl
        string str;
        for(auto& ch:data)
        {
            if(ch==',')  //Go all the way to "," and take out the previous element
            {
                dataArray.push_back(str);  //Put the extracted strings into the list one by one
                str.clear();
            }else
                str.push_back(ch);
        }
        if(!str.empty())
        {
            dataArray.push_back(str);
            str.clear();
        }
        return rdeserialize(dataArray);
    }
};

Tags: Algorithm data structure leetcode

Posted on Sat, 06 Nov 2021 01:48:39 -0400 by egmax