Simple Python Solution | faster than 98.16% | Detailed Comments | Easy to Understand
\n# O(n) time and space complexity for both serialization and \n# deserialization\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(s
```\n# O(n) time and space complexity for both serialization and \n# deserialization\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n\nclass Codec:\n\n    def serialize(self, root: TreeNode) -> str:\n        """Encodes a tree to a single string.\n        """\n        # if we see a None\n        if not root:\n            return "-1"\n        # Otherwise we serialize root, roo.left and root.right\n        # preorder traversal\n        return str(root.val) + ","+self.serialize(root.left) + "," + self.serialize(root.right)\n        \n\n    def deserialize(self, data: str) -> TreeNode:\n        """Decodes your encoded data to tree.\n        """\n        # from preorder list to tree\n        def helper(dq): \n            # using the dq we deserialize one by one\n            value = dq.popleft()\n            # if we see -1, means we need to form null node\n            if value == -1:\n                return None\n            # form the actual node\n            node = TreeNode(value)\n            # form node\'s left\n            node.left = helper(dq)\n            # form node\'s right\n            node.right = helper(dq)\n            \n            return node\n        \n        # at first get the node integer vals from the serial of \n        # the tree \n        #print(data)\n        data = map(int,data.split(","))\n        # form a deque needed to deserialize\n        dq = deque(data)\n        # we call helper with the deque list\n        return helper(dq)\n        \n        \n\n# Your Codec object will be instantiated and called as such:\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# tree = ser.serialize(root)\n# ans = deser.deserialize(tree)\n# return ans\n```\nRuntime: 64 ms, faster than 98.16% of Python3 online submissions for Serialize and Deserialize BST.
[]