The problem involves designing an algorithm to serialize and deserialize a binary search tree (BST). Serialization is the process of converting a BST to a string format, and deserialization is the inverse process, converting a string back to a BST.
Problem Specifications:
Codec
with two methods:
serialize(root)
: Encodes a BST to a string.deserialize(data)
: Decodes the string back to a BST.class Codec:
def serialize(self, root):
"""Encodes a BST to a single string.
:type root: TreeNode
:rtype: str
"""
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
Note:
The standard approach to serialize and deserialize a BST involves leveraging its properties. We’ll use Pre-order Traversal (Root-Left-Right) for serialization because it naturally fits the requirement to reconstruct the tree uniquely during deserialization due to the BST properties.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Codec:
def serialize(self, root):
"""Encodes a BST to a single string."""
def preorder_traverse(node):
return [str(node.val)] + preorder_traverse(node.left) + preorder_traverse(node.right) if node else []
return ' '.join(preorder_traverse(root))
def deserialize(self, data):
"""Decodes your encoded data to tree."""
if not data:
return None
values = list(map(int, data.split()))
def build_tree(min_val, max_val):
if values and min_val < values[0] < max_val:
val = values.pop(0)
node = TreeNode(val)
node.left = build_tree(min_val, val)
node.right = build_tree(val, max_val)
return node
return None
return build_tree(float('-inf'), float('inf'))
# Example usage:
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# ser = codec.serialize(root)
# deser = codec.deserialize(ser)
# assert codec.serialize(deser) == ser
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?