Python preorder recursive traversal

  • 7
    def serialize(self, root):
        preorder = ''
        if not root:
            preorder += ',None'
            return preorder
        preorder += ','+str(root.val)
        preorder += self.serialize(root.left)
        preorder += self.serialize(root.right)
        return preorder
    def deserialize(self, encode_data):
        pos = -1
        data = encode_data[1:].split(',')
        for i in xrange(len(data)):
            if data[i] == 'None':
                data[i] = None
                data[i] = int(data[i])
        root, count = self.buildTree(data, pos)
        return root
    def buildTree(self, data, pos):
        pos += 1
        if pos >= len(data) or data[pos]==None:
            return None, pos
        root = TreeNode(data[pos])
        root.left, pos = self.buildTree(data, pos)
        root.right, pos = self.buildTree(data, pos)
        return root, pos

  • 2


    "Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless."

  • 0

    I missed that.. OK I try it again.

  • 0

    I have changed it!! I think this version is fine now. thx

  • 0

    Closer, but still not quite. Our serialize is supposed to return a string, not a list:

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

  • 1

    Yep! I just change it!!! Thx I miss that

Log in to reply

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