Serialization turns a data structure or object into a sequence of bits so it can be stored in a file or memory buffer, or sent over a network connection, and rebuilt 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 the algorithm works. A binary search tree must serialize to a string, and that string must deserialize back to the original tree structure.
The encoded string should be as compact as possible.
Function Signature
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
...
def deserialize(self, data: str) -> Optional[TreeNode]:
...
Rules
-
TreeNode
is provided, with fields
val
,
left
and
right
. A missing child is
None
.
-
In the examples, a tree is written as a level-order list with
None
for a missing child and trailing
None
values left out.
[]
is the empty tree, passed as
root = None
.
-
The input is a binary search tree in the strict sense: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. All values are therefore distinct.
-
The checker calls
serialize
on one
Codec
instance and
deserialize
on a separate one, passing only the string. The tree that
deserialize
returns must have the same values in the same left and right positions as the input. The output shown in each example is that returned tree.
-
Only the round trip is checked. Compactness is the design goal, so keep the string as short as you can.
Constraints
-
The number of nodes in the tree is in the range
[0, 10^4]
.
-
0 <= Node.val <= 10^4
-
The input tree is guaranteed to be a binary search tree.
Examples
Input: root = [2,1,3]
Output: [2,1,3]
The root 2 has left child 1 and right child 3. Decoding the string must return this same three-node tree.
Input: root = []
Output: []
The empty tree must survive the round trip: deserialize receives whatever string serialize produced for it and returns None.
Input: root = [5,3,8,1,4,None,9]
Output: [5,3,8,1,4,None,9]
Node 3 has children 1 and 4, and node 8 has only a right child, 9. The rebuilt tree must put 9 on the right of 8 and leave the left slot of 8 empty.