Serialize and Deserialize Binary Tree

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Tags: Tree

Try It!

Discussion

Video

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
        """
        if not root:
            return 'n'
        
        val = str(root.val)
        left = self.serialize(root.left)
        right = self.serialize(root.right)
        return val + ',' + left + ',' + right

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        self.data = data
        if self.data[0] == 'n':
            return None
        
        first_break = self.data.find(',')
        node = TreeNode(int(self.data[:first_break]))
        node.left = self.deserialize(self.data[first_break + 1:])
        second_break = self.data.find(',')
        node.right = self.deserialize(self.data[second_break + 1:])
        return node

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