Python preorder recursive traversal


  • 7
    A
    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
            else:
                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

    Quote:

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


  • 0
    A

    I missed that.. OK I try it again.


  • 0
    A

    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
    A

    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.