Leetcode 297 Solution

This article provides solution to leetcode question 297 (serialize-and-deserialize-binary-tree)

https://leetcode.com/problems/serialize-and-deserialize-binary-tree

Solution

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

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """

        tokens = []

        def _serialize(node):
            nonlocal tokens

            if node == None:
                tokens.append("#")
                return

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

        _serialize(root)

        return " ".join(tokens)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        tokens = data.split(" ")

        i = 0
        def _deserialize():
            nonlocal i

            if i == len(tokens):
                return None

            if 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:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))