My Python Preorder + Inorder Solution


  • 0
    class Codec:
        def preorder(self, root):
            return '' if not root else str(root.val) + "#" + self.preorder(root.left) + "#" +  self.preorder(root.right) 
            
        def inorder(self, root):
            return '' if not root else self.inorder(root.left) + "#" + str(root.val) + "#" + self.inorder(root.right) 
            
        def serialize(self, root):
            return self.inorder(root) + "$$" + self.preorder(root)
            
        def buildTree(self, preorder, inorder):
            if not inorder:
                return None
            node = TreeNode(preorder[0])
            index = inorder.index(preorder[0])
            node.left = self.buildTree(preorder[1:index+1], inorder[:index])
            node.right = self.buildTree(preorder[index+1:], inorder[index+1:])
            return node
        
        def deserialize(self, data):
            inorder, preorder = data.split('$$')
            inorder = [int(i) for i in inorder.split("#") if i != '']
            preorder = [int(i) for i in preorder.split("#") if i != '']
            
            return self.buildTree(preorder, inorder)
    

Log in to reply
 

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