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. Daily Scrum Meeting ——ZeroDay(Beta)12.08

    算是BETA冲刺的前奏,不算正式冲刺

  2. call()与apply()

    1.obj1.method1.call(obj2,argument1,argument2) call的作用就是把obj1的方法放到obj2上使用 2. add 来替换 sub,add.call(sub ...

  3. NOIP2009分数线划定【B004】

    [B004]分数线划定[难度B]—————————————————————————————————————————————————————————————————————————— [题目要求] 世博 ...

  4. 如何使用PL/SQL Developer查看和杀掉session

    http://jingyan.baidu.com/article/3ea51489eb65b152e61bba8b.html

  5. Leetcode Trapping Rain Water

    Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...

  6. BFC给我的帮助以及对hasLayout的认识

    布局的时候经常想让一个或几个元素并并排的放在一起,有时给其中的一个浮动,元素是在一行了,可还是都左边重叠了,总是这样那样改来改去,小白的我也是醉了! 今天偶然间看到了了BFC这个东东,虽然现在还是不是 ...

  7. Django分析之使用redis缓存服务器

    时间长没有更新了,这段时间一直忙着一个项目,今天就记录一个现在经常会用到的技术吧. redis相信大家都很熟悉了,和memcached一样是一个高性能的key-value数据库,至于什么是缓存服务器, ...

  8. JavaScript、全选反选-课堂笔记

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. vmstat和iostat

    一.vmstat1.命令示例#vmstat 5每5秒输出一次 2.输出详解procs -----------memory---------- ---swap-- -----io---- --syste ...

  10. tensorfolw配置过程中遇到的一些问题及其解决过程的记录(配置SqueezeDet: Unified, Small, Low Power Fully Convolutional Neural Networks for Real-Time Object Detection for Autonomous Driving)

    今天看到一篇关于检测的论文<SqueezeDet: Unified, Small, Low Power Fully Convolutional Neural Networks for Real- ...