A simple Python solution

  • 0

    the serialization is trivial, for deserialization you only need to record the index of the Node None. [beats 84.4%]

    class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        :type root: TreeNode
        :rtype: str
        tree_str = []
        self.preOrder(tree_str, root)
        return ",".join([str(node) for node in tree_str])
    def preOrder(self, tree_str, root):
        if not root:
        self.preOrder(tree_str, root.left)
        self.preOrder(tree_str, root.right)
    def deserialize(self, data):
        """Decodes your encoded data to tree.
        :type data: str
        :rtype: TreeNode
        _, root = self.deserializeHelper(data.split(","), 0)
        return root
    def deserializeHelper(self, data, i):
        if i >= len(data) or data[i] == "#":
            return i, None
        root = TreeNode(int(data[i]))
        index, root.left = self.deserializeHelper(data, i+1)
        index, root.right = self.deserializeHelper(data, index+1)
        return index, root

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.