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.

So the first question is: what is the difference between this and #297?

This here is BST, however, in #297, it's BT. "The encoded string should be as compact as possible" here. The special property of binary search trees compared to general binary trees allows a more compact encoding. So while the solutions to problem #297 still work here as well, they're not as good as they should be.

For general BT, to reconstruct the tree, we need the information of both in-order and pre-order, or in-order and post-order. We've practised that already.

However, as a BST, just the information of pre-order or post-order is sufficient to rebuild the tree.

The encoded string is also most compact, since we do not need to keep tract of information of 'Null nodes'.

Example:   4

     2       6

1   3   5    7

The pre-order encoding is: "4213657". It is easy to tell "4" is root, "213" is left tree, "657" is right tree. We can use a Queue to implement this, very convenient.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec { // Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "";
StringBuilder res = new StringBuilder();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node!=null) {
if (node != null) {
res.append(node.val).append(" ");
stack.push(node);
node = node.left;
}
else {
node = stack.pop().right;
}
}
return res.toString().trim();
} // Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data==null || data.length()==0) return null;
String[] nodes = data.split(" ");
Queue<Integer> queue = new LinkedList<>();
for (String node : nodes) {
queue.offer(Integer.valueOf(node));
}
return buildTree(queue);
} public TreeNode buildTree(Queue<Integer> queue) {
if (queue.isEmpty()) return null;
TreeNode root = new TreeNode(queue.poll());
Queue<Integer> leftNodeVals = new LinkedList<>();
while (!queue.isEmpty() && queue.peek()<=root.val) {
leftNodeVals.offer(queue.poll());
}
root.left = buildTree(leftNodeVals);
root.right = buildTree(queue);
return root;
}
} // Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

Leetcode: Serialize and Deserialize BST的更多相关文章

  1. [LeetCode] Serialize and Deserialize BST 二叉搜索树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  2. 【LeetCode】449. Serialize and Deserialize BST 解题报告(Python)

    [LeetCode]449. Serialize and Deserialize BST 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/pro ...

  3. [LeetCode] Serialize and Deserialize N-ary Tree N叉搜索树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  4. [leetcode]449. Serialize and Deserialize BST序列化与反序列化BST

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  5. [leetcode]449. Serialize and Deserialize BST序列化反序列化二叉搜索树(尽量紧凑)

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  6. LeetCode 449. Serialize and Deserialize BST

    原题链接在这里:https://leetcode.com/problems/serialize-and-deserialize-bst/description/ 题目: Serialization i ...

  7. 【leetcode】449. Serialize and Deserialize BST

    题目如下: Serialization is the process of converting a data structure or object into a sequence of bits ...

  8. 449. Serialize and Deserialize BST

    https://leetcode.com/problems/serialize-and-deserialize-bst/#/description Serialization is the proce ...

  9. [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

随机推荐

  1. 如何使用的Ue4自带的SQLiteSupport

    在UE4.6版本加入的模块.可以让开发者使用SQLite数据库.SQlite是个轻量型的本地数据库. 我下面就来介绍一下如何使用这个模块. 第一步:下载SQLite源代码以及SQLite GUI管理工 ...

  2. java文件下载,上传,解压方法

    1.文件下载(亲测可用) private static final int BUFFER = 2 * 1024;// 缓冲区大小(2k)private boolean isSuccess = true ...

  3. 10.this关键字

    ①在类的方法定义中使用的this关键字代表使用该方法的对 象的引用 ②当必须指出当前使用方法的对象是谁时要使用this ③有时使用this处理方法中成员变量和参数重名的情况 ④this可以看做是一个变 ...

  4. [转载]C++堆栈的入门学习

    申明:   转自    http://www.cnblogs.com/pengshao/archive/2011/12/26/2301461.html 头文件stackDemo.h #pragma o ...

  5. Learn ZYNQ (9)

    创建zybo cluster的spark集群(计算层面): 1.每个节点都是同样的filesystem,mac地址冲突,故: vi ./etc/profile export PATH=/usr/loc ...

  6. WM_COPYDATA进程间通信方案

    连续在两个公司使用WM_COPYDATA实现进程间通信了,整理一下 具体步骤: 一.   进程A通过ShellExecute启动进程B, 将用于通信的窗口句柄hWndA(已强转为int值)通过命令行参 ...

  7. JQuery实现方法,简单示例

    function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var eleme ...

  8. redis服务器

    Redis是一个Key-Value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括 string(字符串 ). list(链表). set(集合)和 zset(有序集合). ...

  9. JQ第三天//基本纯代码

    一.让图片飞 代码:<script type="text/javascript">        $(function () {            $(docume ...

  10. 带你玩转JavaWeb开发之六-mysql基本语法详解及实例(1)

    1.1.1    对数据库的表进行操作 1.1.1.1   对数据库中表进行创建 [语法:] create table 表名( 列名 列类型 [列约束], 列名 列类型 [列约束], 列名 列类型 [ ...