二叉树的序列化与反序列化

来源:互联网 发布:淘宝美工都需要做什么 编辑:程序博客网 时间:2024/05/17 08:35

顺便说一下,今天做题的时候也用到了stringstream这个类,是二叉树的序列化和反序列化。

  题目链接:http://www.lintcode.com/zh-cn/problem/binary-tree-serialization/

v二叉树的序列化和反序列化

  设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

v思路:

  通过先序遍历建立二叉树的序列化,其中空子树用'#'来表示。反序列化的时候呢,遇到'#'就停止递归构造。另外序列化的时候是将整数通过stringstream转换成字符串,反序列化是将字符串通过stringstream转换成整数。

复制代码
/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * This method will be invoked first, you should design your own algorithm      * to serialize a binary tree which denote by a root node to a string which     * can be easily deserialized by your own "deserialize" method later.     */    bool first;        template<typename out_type, typename in_value>    out_type convert(const in_value & t){        stringstream stream;        stream<<t;//向流中传值        out_type result;//这里存储转换结果        stream>>result;//向result中写入值        return result;    }        void pre_order(TreeNode *root, string &s){        if(root){            string tmp = convert<string>(root->val);            if(!first)                s+= " "+tmp;            else {                first = false;                s+=tmp;            }            pre_order(root->left, s);            pre_order(root->right, s);        } else {            if(first)                s+='#';            else {                first = false;                s+=" #";            }        }    }    string serialize(TreeNode *root) {        // write your code here        string s="";        first = true;        pre_order(root, s);//先序实现序列化        return s;    }        stringstream ss;    void buildT(TreeNode * &T){        string s;        ss>>s;        if(s == "#") return ;        int val = convert<int>(s);        T = new TreeNode(val);        buildT(T->left);        buildT(T->right);    }        /**     * This method will be invoked second, the argument data is what exactly     * you serialized at method "serialize", that means the data is not given by     * system, it's given by your own serialize method. So the format of data is     * designed by yourself, and deserialize it here as you serialize it in      * "serialize" method.     */    TreeNode *deserialize(string data) {        // write your code here        TreeNode *T = NULL;        ss.str("");        ss<<data;        buildT(T);        return T;    }};