剑指 Offer 37. 序列化二叉树(困难)

发布时间 2023-08-16 21:36:34作者: 孜孜不倦fly

题目:

class Codec {
public:
    void rserialize(TreeNode* root, string& str){      //编码递归函数:将树按照前序遍历,放入str字符串中。每个节点元素用','分隔
        if(root==nullptr){      //如果遇到空节点,写入"none"。
            str+="none,";
        }
        else{
            str+=to_string(root->val)+',';      //要将节点元素用to_string转为字符串
            rserialize(root->left, str);
            rserialize(root->right, str);
        }
    }
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {      //将树转化为字符串result
        string result;
        rserialize(root, result);
        return result;
    }


    TreeNode* rdeserialize(list<string>& arr){      //反序列化的时候只能用list,用vector会超时
        if(arr.front()=="none"){      //如果列表元素为"none",直接返回空节点
            arr.erase(arr.begin());      //记得擦除遍历过的列表元素
            return nullptr;
        }
        TreeNode* root=new TreeNode(stoi(arr.front()));      //列表元素不为"none",创建新的树节点。要用stoi将字符串转为int整型
        arr.erase(arr.begin());      //记得擦除遍历过的列表元素
        root->left=rdeserialize(arr);
        root->right=rdeserialize(arr);
        return root;      //返回根节点
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        list<string> arr;
        string str;
        for(auto& ch:data){      //创建list元素列表
            if(ch==','){      //遇到分隔符就说明str收集好了一个节点元素
                arr.push_back(str);
                str.clear();    //放入一个列表元素后,清除str,收集新的节点元素
            }
            else{
                str.push_back(ch);      //没有遇到分隔符,用str收集该节点元素
            }
        }
        /*if(!str.empty()){
            arr.push_back(str);
            str.clear();
        }*/
        return rdeserialize(arr);
    }
};

以上方法转自力扣官方