Serialize and Deserialize Binary Tree

Tree, Design

Hard

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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Example:

You may serialize the following tree:

    1
   / \
  2   3
     / \
    4   5

as 
"[1,2,3,null,null,4,5]"

Clarification:The above format is the same ashow LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

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

Solution & Analysis

Pre-Oder Traversal:

The preorder DFS traverse follows recursively the order of root -> left subtree -> right subtree.

用一个辅助的queue,存入data.split(",")之后的元素,这样在构建树时,就可以按照相同的顺序:root -> left subtree -> right subtree

Complexity Analysis

  • Time complexity : in both serialization and deserialization functions, we visit each node exactly once, thus the time complexity is O(N), whereNNis the number of nodes, _i.e._the size of tree.

  • Space complexity : in both serialization and deserialization functions, we keep the entire tree, either at the beginning or at the end, therefore, the space complexity is O(N).

10 ms, faster than 92.02%

via @cdai -- 以下:代码比较简洁,但是serial的部分不是很readable的地方在于,何时加delimiter ","

优点在保持了末尾不会有多余",", 但是逻辑上比较缠绕,一会pass by reference,一会返回值。因此尽管代码比较简洁,不推荐在面试中使用

Breadth-first Search - Queue

Serialize时类似 pre-order traversal. 这里为了节省空间,删去了末尾的"#",虽然deserialized的时候并无影响。

Deserialize的时候要从左边节点开始填充,也就是说只有i % 2 == 1时才从queue中poll(),如果不为null,再生成新节点放入queue中。

Reference

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/discuss/74253/Easy-to-understand-Java-Solution

https://www.jiuzhang.com/solutions/binary-tree-serialization/#tag-other

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/discuss/74260/Recursive-DFS-Iterative-DFS-and-BFS

Last updated

Was this helpful?