Similar Problems

Similar Problems not available

Serialize And Deserialize Bst - Leetcode Solution

Companies:

LeetCode:  Serialize And Deserialize Bst Leetcode Solution

Difficulty: Medium

Topics: binary-search-tree depth-first-search string breadth-first-search design tree binary-tree  

Problem:

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 search tree. There is no restriction on how you serialize/deserialize the binary search tree, you must ensure that it can be reconstructed.

The input data will only contain the root of the binary search tree.

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, 104].

0 <= Node.val <= 104

The input data is guaranteed to be a valid binary search tree.

Solution:

Serialization is the process of converting an object into a format that can be easily stored or transmitted. In the case of a binary search tree, we can serialize it by traversing the tree - in this case, we will use pre-order traversal.

If a node is null, we will add a special marker (e.g. '#') to indicate that it is null. Otherwise, we will add the node's value to the serialization, then serialize its left and right subtrees recursively.

To deserialize the serialized tree, we can simply reverse the process. We start with the first value in the serialization and create a new node with that value. Then we recursively deserialize the left and right subtrees, using the special marker to indicate when a node is null.

Here is a detailed implementation of the solution in Python:

""" 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: TreeNode) -> str: """Encodes a tree to a single string. """ def traverse(node): if not node: return '#' return str(node.val) + ',' + traverse(node.left) + ',' + traverse(node.right)

    return traverse(root)

def deserialize(self, data: str) -> TreeNode:
    """Decodes your encoded data to tree.
    """
    def build_tree(vals):
        if not vals:
            return None
        if vals[0] == '#':
            vals.pop(0)
            return None
        node = TreeNode(int(vals[0]))
        vals.pop(0)
        node.left = build_tree(vals)
        node.right = build_tree(vals)
        return node
    
    vals = data.split(',')
    return build_tree(vals)
    

Your Codec object will be instantiated and called as such:

ser = Codec()

deser = Codec()

ans = deser.deserialize(ser.serialize(root))

Serialize And Deserialize Bst Solution Code

1