栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode 449. 序列化和反序列化二叉搜索树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode 449. 序列化和反序列化二叉搜索树

题目描述

449. 序列化和反序列化二叉搜索树

解法

还是老问题,我们要还原唯一一棵二叉树非中 + 前或中 + 后两种组合不可,之前在 LeetCode 297. 二叉树的序列化与反序列化 一题中可以唯一确定一棵二叉树是因为我们保存了空指针信息

但是对于 BST 也是一个特殊情况,考虑 BST 的特性,我们可以通过如下操作唯一确定

考虑前序遍历一棵 BST,仅保存节点值序列化 BST。那么在反序列化时,我们根据从字符串分割得到的前序遍历结果 n o d e s nodes nodes 就可以递归还原这棵 BST,对于连续段 n o d e s [ l o , h i ] nodes[lo, hi] nodes[lo,hi]

  • n o d e s [ l o ] nodes[lo] nodes[lo] 必是当前段的根节点,接着在 [ l o , h i ] [lo, hi] [lo,hi] 中搜索第一个比根节点值大的位置 r i g h t _ s t a r t right_start right_start
  • n o d e s [ l o ] nodes[lo] nodes[lo] 的左子树就可以在 [ l o + 1 , r i g h t _ s t a r t − 1 ] [lo + 1, right_start-1] [lo+1,right_start−1] 段中递归构造
  • n o d e s [ l o ] nodes[lo] nodes[lo] 的右子树就可以在 [ r i g h t _ s t a r t , h i ] [right_start, hi] [right_start,hi] 段中递归构造
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string str = "";
        if (root == nullptr) return str;
        serialize_helper(root, str);
        return str;
    }
    void serialize_helper(TreeNode* root, string& str)
    {
        if (root == nullptr) return;
        str += to_string(root->val) + ',';
        serialize_helper(root->left, str);
        serialize_helper(root->right, str);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        vector nodes;
        string str;
        for (auto c: data)
        {
            if (c == ',') 
            {
                nodes.push_back(str);
                str.clear();
            }
            else 
            {
                str.push_back(c);
            }
            
        }
        return deserialize_helper(0, nodes.size() - 1, nodes);
    }

    TreeNode* deserialize_helper(int lo, int hi, vector& nodes){
        if (lo > hi) return nullptr;
        int right_start = lo + 1, val = stoi(nodes[lo]);
        TreeNode* root = new TreeNode(val);
        while (right_start <= hi && stoi(nodes[right_start]) < val) right_start++;
        root->left = deserialize_helper(lo + 1, right_start - 1, nodes);
        root->right = deserialize_helper(right_start, hi, nodes);
        return root;

    }

};

// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876431.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号