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

/**
 * 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 rserialize(TreeNode *root,string& str){
        if(root==nullptr){
            str+="None,";
        }else {
            str+=to_string(root->val)+",";
            rserialize(root->left,str);
            rserialize(root->right,str);
        }
    }
    //序列化
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string ans;
        rserialize(root,ans);
        return ans;
    }
    //将List中的数值转化为树
    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;//将数值加入到list中
        string str;
        for(auto &ch:data){
            if(ch==','){
                dataArray.push_back(str);
                str.clear();
            }else {
                str.push_back(ch);
            }
        }
        if(!str.empty()){
            dataArray.push_back(str);
            str.clear();
        }
        return rdeserialize(dataArray);
    }
};