https://leetcode.com/problems/serialize-and-deserialize-bst

My idea to solve this problem is to use Problem 1008. Construct Binary Search Tree from Preorder Traversal. So:

  1. For our serialization we just get preorder traversel (iterative or recursion, whatever you want, I used iterative, using stack).
  2. For deserialization we use solution with O(n) time complexity: we give the function two bounds - up and down: the maximum number it will handle. The left recursion will take the elements smaller than node.val and the right recursion will take the remaining elements smaller than bound.

Complexity: both for serialization and deserialization is O(n), because self.index will be increased by one on each iteration.

class Codec:
    def serialize(self, root):
        if not root: return ""
        stack, out = [root], []
        while stack:
            cur = stack.pop()
            out.append(cur.val)
            for child in filter(None, [cur.right, cur.left]):
                stack += [child]
                
        return ' '.join(map(str, out))
        
    def deserialize(self, data):
        preorder = [int(i) for i in data.split()]
        def helper(down, up):
            if self.idx >= len(preorder): return None
            if not down <= preorder[self.idx] <= up: return None
            root = TreeNode(preorder[self.idx])
            self.idx += 1
            root.left = helper(down, root.val)
            root.right = helper(root.val, up)
            return root
            
        self.idx = 0
        return helper(-float("inf"), float("inf"))

If you like the solution, you can upvote it on leetcode discussion section: Problem 0449