[LeetCode]Serialize and Deserialize Binary Tree

题目链接: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.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.


题目描述:

题目要求对一个用TreeNode链表存储的二叉树进行序列化与反序列化,最后得到原始的TreeNode链表则说明成功。

因为题目并不关心中间过程得到的序列化串,因此不必拘泥于LeetCode常用的表示法,而可以使用自己的表示法。

为了方便重建,我们使用前序遍历,并且每当碰到一个NULL孩子,就存储一个#字符。

这样来说,在存储题目给出的树的时候,我们会得到[1,2,#,#,3,4,#,#,5,#,#,]这么一个字符串。

在还原时,只需要按照前序遍历的方式递归着解析这个序列化串,使用的核心方法为字符串的substr、find方法,该方法常用的形式有两种:①str.substr(location),这个方法会返回str从location开始到结尾的字串。②str.substr(location,len),这个方法会返回[location,location+len)区间的字符串,注意右面为开区间。str.find(charset)将返回str中第一个匹配到的charset的位置。

【具体实现】

为了方便递归,我们定义两个类的私有方法。

1.序列化

按照前序遍历的规则访问root,对于root为NULL的情况拼接#,其他情况拼接结点的数字,为了实现数字到字符串的转换,使用stringstream。

2.反序列化

递归函数的参数为(TreeNode *&root, string &data),根据data分割出的值val来决定root的值,如果val是#,则说明这是一个空结点,直接令root=NULL,否则创建一个新的TreeNode作为root,注意解析val值使用的是C函数atoi,需要用字符串的c_str()方法得到char*字符串,继续递归root的左右儿子,注意此时传入的data是已经去掉处理完部分的字串。反序列化的递归顺序与前序遍历保持一致。

代码如下:

/**
 * 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 res;
        preOrderSerialize(root,res);
        cout << res;
        return res;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        TreeNode *root = NULL;
        preOrderDeserialize(root,data);
        return root;
    }
private:

    void preOrderSerialize(TreeNode *root, string &str){
        if(!root){
            str += "#,";
            return;
        }
        stringstream ss;
        ss << root->val;
        str += ss.str();
        str += ",";
        preOrderSerialize(root->left,str);
        preOrderSerialize(root->right,str);
    }
    
    void preOrderDeserialize(TreeNode *&root, string &data){
        if(data.length() == 0) return;
        string tmp = data.substr(0,data.find(','));
        data = data.substr(data.find(',')+1);
        if(tmp.compare("#") == 0) root = NULL;
        else{
            root = new TreeNode(atoi(tmp.c_str()));
            preOrderDeserialize(root->left,data);
            preOrderDeserialize(root->right,data);
        }
    }
    
};



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


posted on 2015-11-06 14:36  张大大123  阅读(134)  评论(0编辑  收藏  举报

导航