Sword refers to Offer 37. Serialized binary tree (pre-order traversal, post-order traversal, hierarchical traversal)

Friday, February 12, 2021, the weather is fine [Don’t lament the past, don’t waste the present, don’t fear the future]


1. Introduction

Sword Finger Offer 37. Serialized Binary Tree
Insert picture description here

2. Solution

2.1 Pre-order traversal (or post-order traversal)

Preorder traversal is relatively simple to apply recursion during deserialization, and postorder traversal can be traversed from back to front during deserialization, and the order becomes "root—>right—>left", code and preorder traversal It's just a slight difference.

The binary tree obtained by the in-order traversal is not unique, and the deserialized binary tree cannot be guaranteed to be the original tree , as shown in the figure below.
Insert picture description here
Picture source TIM_Y , invaded and deleted.

The code for pre-order traversal is as follows:

/**
 * 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:
    // 序列化递归函数(前序遍历)
    void dfs(TreeNode* root, string& s){
    
    
        if(root==nullptr) s.append("#,");
        else{
    
    
            s.append(to_string(root->val));
            s.append(",");
            dfs(root->left, s);
            dfs(root->right, s);
        }
    }

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
    
    
        string s;
        dfs(root,s);
        return s;
    }

    // 反序列化递归函数(前序遍历)
    void dese(vector<string> &node, int& i, TreeNode* &root){
    
    
        if(i<node.size()){
    
    
            if(node[i]=="#"){
    
    
                ++i;
                root = nullptr;
                return;
            }
            root = new TreeNode(stoi(node[i]));
            ++i;
            dese(node,i,root->left);
            dese(node,i,root->right);
        }
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
    
    
        // 手动实现split字符串分割函数 
        vector<string> node;
        stringstream ss(data);
        string word;
        while(getline(ss,word,','))
            node.emplace_back(word);

        TreeNode* root = nullptr;
        int i = 0;
        dese(node, i, root);
        return root;
    }
};

2.2 Sequence traversal

Sequence traversal, deserialization is the key point: first judge the tree is empty, then put the root node into the team, place the left and right children of the root node, and decide whether to enter the queue according to whether the left and right children are empty . The child node repeats the process experienced by the root node (in bold).

/**
 * 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;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){
    
    
            TreeNode* tmp = que.front();
            que.pop();
            if(tmp==nullptr) s.append("#,");
            else{
    
    
                s.append(to_string(tmp->val));
                s.append(",");
                que.push(tmp->left);
                que.push(tmp->right);
            }
        }
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
    
    
        if(data.empty() || data[0]=='#') return nullptr;
        stringstream ss(data);
        vector<string> node;
        string word;
        while(getline(ss, word, ','))
            node.emplace_back(word);

        TreeNode* root = new TreeNode(stoi(node[0]));
        queue<TreeNode*> que;
        que.push(root);
        int i = 1;
        // 反序列化是重点
        while(!que.empty()){
    
    
            TreeNode* tmp = que.front();
            que.pop();
            // 安置左孩子
            if(node[i]!="#"){
    
    
                tmp->left = new TreeNode(stoi(node[i]));
                que.push(tmp->left);
            }
            ++i;
            // 安置右孩子
            if(node[i]!="#"){
    
    
                tmp->right = new TreeNode(stoi(node[i]));
                que.push(tmp->right);
            }
            ++i;
        }
        return root;
    }
};

references

"Sword Finger Offer Second Edition"

https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/solution/mian-shi-ti-37-xu-lie-hua-er-cha-shu-ceng-xu-bian-/

https://www.nowcoder.com/discuss/436465?type=0&order=0&pos=25&page=0&channel=-2&source_id=discuss_center_0

Guess you like

Origin blog.csdn.net/m0_37433111/article/details/113796365