algoadvance

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:

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:

Clarifying Questions:

Strategy:

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.

Serialize:

  1. Perform a pre-order traversal of the BST.
  2. Convert the tree nodes’ values to a string, separated by spaces.

Deserialize:

  1. Convert the string back to a list of integers.
  2. Reconstruct the BST using the list of values maintaining the BST property.

Code Implementation:

# 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

Time Complexity:

Try our interview co-pilot at AlgoAdvance.com