Skip to content
LC-0297 Hard LeetCode

297. Serialize and Deserialize Binary Tree

Read the full problem statement on LeetCode.
Difficulty: hard Acceptance: 59% Topics: String, Tree, Depth-First Search, Breadth-First Search, Design, Binary Tree
View full problem on LeetCode
Reference solution (spoiler · python)
# 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
        """

        def preorder(node):
            if not node:
                return "None,"
            return str(node.val) + "," + preorder(node.left) + preorder(node.right)

        return preorder(root)

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

        :type data: str
        :rtype: TreeNode
        """

        def build_tree(values):
            if values[0] == "None":
                values.pop(0)
                return None

            root = TreeNode(int(values.pop(0)))
            root.left = build_tree(values)
            root.right = build_tree(values)

            return root

        values = data.split(",")
        return build_tree(values[:-1])


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

Solution from kamyu104/LeetCode-Solutions · MIT