Why my recursive python solution is MLE?


  • 0
    J
    class Solution:
    # @param {integer[]} preorder
    # @param {integer[]} inorder
    # @return {TreeNode}
    def buildTree(self, preorder, inorder):
        if not preorder:
            return None
        root=TreeNode(preorder[0])
        if len(preorder)==1:
            root.left=None
            root.right=None
            return root
        flag=inorder.index(preorder[0])
        in1=inorder[:flag]
        in2=inorder[flag+1:]
        pre1=preorder[1:len(in1)+1]
        pre2=preorder[len(in1)+1:]
        root.left=self.buildTree(pre1,in1)
        root.right=self.buildTree(pre2,in2)
        return root

  • 0
    C

    You should do it in place. It means you should pass the start and end index as parameters when carrying out recursion, not the sublist itself, it is so costly in Python.


  • 0
    J

    THANKS so much!


Log in to reply
 

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