Why recursive Python program is memory out limit?


  • 0
    W
    class Solution(object):
        def buildTree(self, preorder, inorder):
            """
            :type preorder: List[int]
            :type inorder: List[int]
            :rtype: TreeNode
            """
            if len(preorder)==0:
                return None
            elif len(preorder)==1:
                return TreeNode(preorder[0])
            root=TreeNode(preorder[0])
            i=inorder.index(preorder[0])
            left=self.buildTree(preorder[1:i+1],inorder[:i])
            right=self.buildTree(preorder[i+1:],inorder[i+1:])
            root.left=left
            root.right=right
            return root

  • 0
    I

    Because preorder[1:i+1] will create a new list.


Log in to reply
 

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