随笔 - 165,  文章 - 0,  评论 - 4,  阅读 - 18023

题目:

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);
    }
};

以上方法转自力扣官方

posted on   孜孜不倦fly  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示