Leetcode 449 Solution

This article provides solution to leetcode question 449 (serialize-and-deserialize-bst)

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

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root: Optional[TreeNode]) -> str:
        """Encodes a tree to a single string.
        """
        tokens = []

        def _serialize(node):
            if not node:
                tokens.append("#")
                return

            tokens.append(str(node.val))
            _serialize(node.left)
            _serialize(node.right)

        _serialize(root)

        return " ".join(tokens)

    def deserialize(self, data: str) -> Optional[TreeNode]:
        """Decodes your encoded data to tree.
        """
        tokens = data.split(" ")

        i = 0
        def _deserialize():
            nonlocal i

            if i == len(tokens) or tokens[i] == "#":
                i += 1
                return None

            node = TreeNode(int(tokens[i]))
            i += 1

            node.left = _deserialize()
            node.right = _deserialize()

            return node

        return _deserialize()


# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans