Python Recursive Solution (DFS-like)


  • 0
    R
    class Codec(object):
    
        # Do a FirstDeepSearch and append each node on the DFS order
        def DFSserialize(self, root, serial):
            if(root == None):
                serial.append('none')
                return serial
            
            serial.append(root.val)
            serial = self.DFSserialize(root.left, serial)
            serial = self.DFSserialize(root.right, serial)
            return serial
            
            serial.append(root.val)
            serial = self.DFSserialize(root.left, serial)
            serial = self.DFSserialize(root.right, serial)
            return serial
    
        def serialize(self, root):
            serial = []
            serial = self.DFSserialize(root, serial)
            return serial
    
    
        # Do a FirstDeepSearch (in a empty Tree) and create each node in the DFS 
        # order (the same order the original Tree was serialized)
        def DFSdeserialize(self, data, i):
            if(data[i] == 'none'):
                return None
            
            root = TreeNode(data[i])
            root.left = self.DFSdeserialize( data, i+1)
            root.right = self.DFSdeserialize(data, i+2)
            del data[i+1]
            del data[i+1]
            return root
    
        def deserialize(self, data):
            root = None
            root = self.DFSdeserialize(data, 0)
            return root
    ´´´

Log in to reply
 

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