[LeetCode] 449. Serialize and Deserialize BST #449
Comments
在discussion看到高票帖子学到的。
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
在discussion看到高票帖子学到的。
|
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性质的方法,姑且就按照之前题目的解法来写吧:
解法一:
另一种方法是层序遍历的非递归解法,这种方法略微复杂一些,我们需要借助queue来做,本质是BFS算法,也不是很难理解,就是BFS算法的常规套路稍作修改即可,参见代码如下:
解法二:
类似题目:
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 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: