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

原题在这里

概述:

  给定一个二叉树的根节点,要求转换为任意字符串,后将该字符串还原二叉树的结构。

硬核手撸:

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec
{
    int id;
    vector<int> tv(TreeNode *r)//node -> vector
    {
        /*
        这里不便用递归法生成数组了,
        用迭代法,但是只能用迭代法二
        */
        vector<int> ans;
        if (!r)
            return ans;
        stack<TreeNode *> st;
        TreeNode *n = r;
        while (!st.empty() || n != nullptr)
        {
            while (n != nullptr)
            {
                ans.emplace_back(n->val);
                st.emplace(n);
                n = n->left;
            }
            ans.emplace_back(-9999);
            n = st.top()->right;
            st.pop();
        }
        return ans;
    }
    TreeNode *vt(vector<int> num)//vector -> node
    {
        //前序遍历构造
        if (id >= num.size() || num[id] == -9999)
            return nullptr;
        TreeNode *r = new TreeNode(num[id]);
        ++id, r->left = vt(num);
        ++id, r->right = vt(num);
        return r;
    }
    vector<int> sv(string s)//string -> vector
    {
        vector<int> ans;
        int num = 0, pd = 1;
        for (char i : s)
        {
            if (i == ' ')
                ans.emplace_back(num * pd), num = 0, pd = 1;
            else if (i == '-')
                pd = -1;
            else
                num = num * 10 + (i - '0');
        }
        return ans;
    }
    string is(int x)//int -> string
    {
        if (x == 0)
            return "0";
        bool pd = false;
        string ans = "";
        if (x < 0)
            pd = true, x = -x;
        while (x)
            ans = (char)(x % 10 + '0') + ans, x /= 10;
        return (pd ? "-" : "") + ans;
    }

public:
    string serialize(TreeNode *root)
    {
        string ans = "";
        vector<int> num = tv(root);//前序遍历转存为数组
        for (int i : num)
            ans += is(i) + ' ';//格式化数组为字符串
        return ans;
    }

    TreeNode *deserialize(string data)
    {
        id = 0;
        return vt(sv(data));//将字符串转换成数组后再还原为二叉树
    }
};
不是很美观

鉴于手撸AC了,就暂时不学习其他代码。

注意一点是,节点转存数组的时候:

  不能使用下文的第一种迭代法

    【在遇到如二叉树[1,2]的时候,遍历节点1,会考虑到右子树为空,导致生成数组为[1,null,2,null,null]】

  只能使用第二种。

引文——二叉树的遍历

【Over】

posted @ 2022-04-01 15:56  Renhr  阅读(24)  评论(0)    收藏  举报