Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

这道题让我们对二叉搜索树序列化和去序列化,跟之前那道Serialize and Deserialize Binary Tree极其相似,虽然题目中说编码成的字符串要尽可能的紧凑,但是我们并没有发现跟之前那题有何不同,而且也没有看到能够利用BST性质的方法,姑且就按照之前题目的解法来写吧:

解法一:

  1. class Codec {
  2. public:
  3.  
  4. // Encodes a tree to a single string.
  5. string serialize(TreeNode* root) {
  6. ostringstream os;
  7. serialize(root, os);
  8. return os.str();
  9. }
  10.  
  11. // Decodes your encoded data to tree.
  12. TreeNode* deserialize(string data) {
  13. istringstream is(data);
  14. return deserialize(is);
  15. }
  16.  
  17. void serialize(TreeNode* root, ostringstream& os) {
  18. if (!root) os << "# ";
  19. else {
  20. os << root->val << " ";
  21. serialize(root->left, os);
  22. serialize(root->right, os);
  23. }
  24. }
  25.  
  26. TreeNode* deserialize(istringstream& is) {
  27. string val = "";
  28. is >> val;
  29. if (val == "#") return NULL;
  30. TreeNode* node = new TreeNode(stoi(val));
  31. node->left = deserialize(is);
  32. node->right = deserialize(is);
  33. return node;
  34. }
  35. };

另一种方法是层序遍历的非递归解法,这种方法略微复杂一些,我们需要借助queue来做,本质是BFS算法,也不是很难理解,就是BFS算法的常规套路稍作修改即可,参见代码如下:

解法二:

  1. class Codec {
  2. public:
  3.  
  4. // Encodes a tree to a single string.
  5. string serialize(TreeNode* root) {
  6. if (!root) return "";
  7. ostringstream os;
  8. queue<TreeNode*> q;
  9. q.push(root);
  10. while (!q.empty()) {
  11. TreeNode *t = q.front(); q.pop();
  12. if (t) {
  13. os << t->val << " ";
  14. q.push(t->left);
  15. q.push(t->right);
  16. } else {
  17. os << "# ";
  18. }
  19. }
  20. return os.str();
  21. }
  22.  
  23. // Decodes your encoded data to tree.
  24. TreeNode* deserialize(string data) {
  25. if (data.empty()) return NULL;
  26. istringstream is(data);
  27. queue<TreeNode*> q;
  28. string val = "";
  29. is >> val;
  30. TreeNode *res = new TreeNode(stoi(val)), *cur = res;
  31. q.push(cur);
  32. while (!q.empty()) {
  33. TreeNode *t = q.front(); q.pop();
  34. if (!(is >> val)) break;
  35. if (val != "#") {
  36. cur = new TreeNode(stoi(val));
  37. q.push(cur);
  38. t->left = cur;
  39. }
  40. if (!(is >> val)) break;
  41. if (val != "#") {
  42. cur = new TreeNode(stoi(val));
  43. q.push(cur);
  44. t->right = cur;
  45. }
  46. }
  47. return res;
  48. }
  49. };

类似题目:

Serialize and Deserialize Binary Tree

Find Duplicate Subtrees

Serialize and Deserialize N-ary Tree

参考资料:

https://leetcode.com/problems/serialize-and-deserialize-bst

https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93260/easy-bfs-java

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Serialize and Deserialize BST 二叉搜索树的序列化和去序列化的更多相关文章

  1. Leetcode:96. 不同的二叉搜索树

    Leetcode:96. 不同的二叉搜索树 Leetcode:96. 不同的二叉搜索树 题目在链接中,点进去看看吧! 先介绍一个名词:卡特兰数 卡特兰数 卡特兰数Cn满足以下递推关系: \[ C_{n ...

  2. LeetCode 95 | 构造出所有二叉搜索树

    今天是LeetCode专题第61篇文章,我们一起来看的是LeetCode95题,Unique Binary Search Trees II(不同的二叉搜索树II). 这道题的官方难度是Medium,点 ...

  3. 数据结构中很常见的各种树(BST二叉搜索树、AVL平衡二叉树、RBT红黑树、B-树、B+树、B*树)

    数据结构中常见的树(BST二叉搜索树.AVL平衡二叉树.RBT红黑树.B-树.B+树.B*树) 二叉排序树.平衡树.红黑树 红黑树----第四篇:一步一图一代码,一定要让你真正彻底明白红黑树 --- ...

  4. C# leetcode 之 096 不同的二叉搜索树

    C# leetcode 之 096 不同的二叉搜索树 题目描述 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 二叉搜索树定义 左子树上所有节点的值小于根节点, 右子树上左右 ...

  5. [LeetCode] Minimum Absolute Difference in BST 二叉搜索树的最小绝对差

    Given a binary search tree with non-negative values, find the minimum absolute difference between va ...

  6. LeetCode #938. Range Sum of BST 二叉搜索树的范围和

    https://leetcode-cn.com/problems/range-sum-of-bst/ 二叉树中序遍历 二叉搜索树性质:一个节点大于所有其左子树的节点,小于其所有右子树的节点 /** * ...

  7. [LeetCode] Inorder Successor in BST 二叉搜索树中的中序后继节点

    Given a binary search tree and a node in it, find the in-order successor of that node in the BST. No ...

  8. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  9. bst 二叉搜索树简单实现

    //数组实现二叉树: // 1.下标为零的元素为根节点,没有父节点 // 2.节点i的左儿子是2*i+1:右儿子2*i+2:父节点(i-1)/2: // 3.下标i为奇数则该节点有有兄弟,否则又左兄弟 ...

随机推荐

  1. 一个由Response.Redirect 引起的性能问题的分析

    现象: 某系统通过单点登录(SSO) 技术验证用户登录.用户在SSO 系统上通过验证后,跳转到某系统的主页上面.而跳转的时间很长,约1分钟以上. 分析步骤: 在问题复现时抓取Hang dump 进行分 ...

  2. 使用F#开发ASP.NET Core应用程序

    .NET Core 里的F# 在.NET Core刚发布时,就已经添加了对F#的支持.但因为当时F#组件还不完整,而一些依赖包并没有放在Nuget上,而是社区自己放到MyGet上,所以在使用dotne ...

  3. 导出BOM表

    1.Report->Bill of Materials for Project 将Value拖上左上角的Grouped Columns 2.在Excel表中全选器件,右键设置"设置单元 ...

  4. 浅析linux内核中的idr机制

    idr在linux内核中指的就是整数ID管理机制,从本质上来说,这就是一种将整数ID号和特定指针关联在一起的机制.这个机制最早是在2003年2月加入内核的,当时是作为POSIX定时器的一个补丁.现在, ...

  5. [C#项目开源] MongoDB 可视化管理工具 (2011年10月-至今)

    正文 该项目从2011年10月开始开发,知道现在已经有整整5年了.MongoDB也从一开始的大红大紫到现在趋于平淡. MongoCola这个工具在一开始定位的时候只是一个Windows版本的工具,期间 ...

  6. php:ci学习笔记1

    ci下载的开发包:     phpstudy的部署: phpstudy的根目录是:D:\WWW 新建目录 cms  把ci开发包的application   system index.php  lic ...

  7. Linux设置开机启动

    开机启动 解决服务器重启,比如断点,导致服务没有启动的烦恼   1.整理机器上面运行的服务,编些成sh脚本,文件为:/home/rc/exec.sh #加载环境变量 source /etc/profi ...

  8. iframe关于滚动条的去除和保留

    iframe嵌入页面后,我们有时需要调整滚动条,例如,去掉全部的滚动条,去掉右边的滚动条且保留底下的滚动条,去掉底下的滚动条且保留右边的滚动条.那么我们应该怎么做呢? 一:去掉全部的滚动条 第一个方法 ...

  9. node.js express安装及示例网站搭建

    1.首先肯定是要安装Node.JS windows cmd依次输入如下命令: cd C:\Program Files\nodejs\ npm install -g expressnpm install ...

  10. iOS 网络流量统计

    在开发中,有时候需要获取流量统计信息.研究发现:通过函数getifaddrs来得到系统网络接口的信息,网络接口的信息,包含在if_data字段中, 有很多信息, 但我现在只关心ifi_ibytes,  ...