LeetCode-297 Serialize and Deserialize Binary Tree

题目描述

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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

题目大意

实现将一颗二叉树序列化和逆序列化的操作(序列化的结果不定,可以自己决定,但要求序列化之后再逆序列化之后的二叉树要与之前的一样)。

示例

E1

You may serialize the following tree:

    1
   / 
  2   3
     / 
    4   5

as "[1,2,3,null,null,4,5]"

解题思路

序列化:dfs遍历二叉树,将二叉树中的结果转为字符串,树结点之间用‘,’分隔开,遇到NULL结点用‘#’表示。

逆序列化:依次遍历字符串,同时dfs建立二叉树。

复杂度分析

时间复杂度:O(N)

空间复杂度:O(N)

代码

/**
 * 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:

    // 将二叉树序列化
    string serialize(TreeNode* root) {
        if(root == NULL)
            return "#";
        return to_string(root->val) + ',' + serialize(root->left) + ',' + serialize(root->right);
    }

    // 将字符串逆序列化
    TreeNode* deserialize(string data) {
        return solve(data);
    }
    
    TreeNode* solve(string& data) {
        if(data[0] == '#') {
            if(data.length() > 1)
                data = data.substr(2);
            return NULL;
        }
        else {
            TreeNode* root = new TreeNode(helper(data));
            root->left = solve(data);
            root->right = solve(data);
            return root;            
        }        
    }
    
private:
    // 查找当前结点所对应的整数并将其表示出来,同时使字符串更新
    int helper(string& s) {
        int pos = s.find(',');
        int res = stoi(s.substr(0, pos));
        s = s.substr(pos + 1);
        return res;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
原文地址:https://www.cnblogs.com/heyn1/p/11156199.html