Serialize And Deserialize BST Problem
Description
LeetCode Problem 449.
Serialization is 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 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.
Example 1:
Input: root = [2,1,3]
Output: [2,1,3]
Example 2:
Input: root = []
Output: []
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.
Solution
Approach: Preorder Values with Bounds
A general binary tree needs null markers to be rebuilt, which is what makes its encoding long. A BST does not: its preorder list of values alone is enough, because the ordering rule tells us where each value goes.
Serialize: write the values in preorder (node, left subtree, right subtree), separated by spaces. An empty tree gives the empty string.
Deserialize: read the values back in the same order with a recursive build(low, high) that builds the subtree whose values lie strictly between low and high:
- If there are no values left, or the next value is not in
(low, high), this subtree is empty: return null without consuming anything. - Otherwise take the value, make a node, and build its left subtree with bounds
(low, value)and then its right subtree with(value, high).
Start with build(-∞, +∞). Preorder puts a node first, then all of its smaller descendants, then all of its larger ones, so the next value either fits the current bounds or belongs to some ancestor's right side. The bounds catch exactly that moment.
preorder "5 3 1 4 8"
5 bounds (-inf, +inf)
├── 3 bounds (-inf, 5)
│ ├── 1 bounds (-inf, 3)
│ └── 4 bounds (3, 5); next value 8 is not in (4, 5), so 4 has no right child
└── 8 bounds (5, +inf)
Each value is read once, so rebuilding is linear.
Complexity: O(n) time for both operations and O(n) space for the string and the value list; the recursion uses O(h), where n is the number of nodes and h the height of the tree.
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string: its values in preorder, no null markers."""
values = []
def preorder(node: Optional[TreeNode]) -> None:
if node is None:
return
values.append(str(node.val))
preorder(node.left)
preorder(node.right)
preorder(root)
return " ".join(values)
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
values = [int(v) for v in data.split()]
next_index = 0 # next preorder value to place
def build(low: float, high: float) -> Optional[TreeNode]:
"""Builds the subtree whose values lie strictly between low and high."""
nonlocal next_index
if next_index == len(values) or not low < values[next_index] < high:
return None # the next value belongs to an ancestor's other side
value = values[next_index]
next_index += 1
node = TreeNode(value)
node.left = build(low, value) # smaller values come first in preorder
node.right = build(value, high)
return node
return build(float("-inf"), float("inf"))
Now write it from memory
Close the write-up and solve it yourself against the tests.