Leetcode: Serialize and Deserialize BST
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的更多相关文章
- [LeetCode] Serialize and Deserialize BST 二叉搜索树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- 【LeetCode】449. Serialize and Deserialize BST 解题报告(Python)
[LeetCode]449. Serialize and Deserialize BST 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/pro ...
- [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 ...
- [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 ...
- [leetcode]449. Serialize and Deserialize BST序列化反序列化二叉搜索树(尽量紧凑)
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
- LeetCode 449. Serialize and Deserialize BST
原题链接在这里:https://leetcode.com/problems/serialize-and-deserialize-bst/description/ 题目: Serialization i ...
- 【leetcode】449. Serialize and Deserialize BST
题目如下: Serialization is the process of converting a data structure or object into a sequence of bits ...
- 449. Serialize and Deserialize BST
https://leetcode.com/problems/serialize-and-deserialize-bst/#/description Serialization is the proce ...
- [LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化
Serialization is the process of converting a data structure or object into a sequence of bits so tha ...
随机推荐
- XCode6 生成prefix.pch文件
XCode6里, 新建工程默认是没有pch文件的,苹果取消pch文件这一点肯定有它的道理,刚开始很多人可能不适应,如果我们想使用pch文件,需要手动添加,添加步骤如下:(依旧直接上图)
- linux 查看Java 进程的内存使用情况
top -b -n 1 | grep java| awk '{print "PID:"$1",mem:"$6",CPU percent:"$ ...
- Java -> 把Excel表格中的数据写入数据库与从数据库中读出到本地 (未完善)
写入:没有关闭流,容错并不完善. private void insertFile(HttpServletRequest request, HttpServletResponse response) t ...
- 诡异的C语言实参求值顺序
学了这么久的C语言,竟然第一次碰到这么诡异的实参求值顺序问题,大跌眼镜.果然阅读面太少了! #include<iostream> void foo(int a, int b, int c) ...
- Leetcode First Missing Positive
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- compass tables 表格 表格常见样式[Sass和compass学习笔记]
demo 源码 地址 https://github.com/qqqzhch/webfans compass 的表格提供了集中常见样式 表格边框 outer-table-borders($width, ...
- ov5640摄像头设备驱动
http://www.cnblogs.com/firege/p/5806121.html (驱动大神) http://blog.csdn.net/yanbixing123/article/detai ...
- ZeroMQ接口函数之 :zmq_ctx_term - 终结一个ZMQ环境上下文
ZeroMQ 官方地址 :http://api.zeromq.org/4-0:zmq_ctx_term zmq_ctx_term(3) ØMQ Manual - ØMQ/4.1.0 Name zmq_ ...
- Python标准异常topic
Python标准异常topic AssertionError 断言语句 (assert) ...
- Screen Orientation for Windows Phone
http://msdn.microsoft.com/en-us/library/windows/apps/jj207002(v=vs.105).aspx