Home > front end >  Why array is accessible deep in the recursive stack while int type does not?
Why array is accessible deep in the recursive stack while int type does not?

Time:04-19

I have a recursive function, and while deep in the recursive stack, I'm surprised that I'm still able to reference an array but not an int-type variable. Why is it so?

    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        ans = 0
        def DFS(root, combination):
            if not root:
                return
            newComb = combination str(root.val)
            if not root.left and not root.right:
                ans  = int(newComb, 2) # ans not accessible
            DFS(root.left, newComb)
            DFS(root.right, newComb)
        DFS(root, "")
        return ans
        ...
        bin = []
        def DFS(root, combination):
            if not root:
                return
            newComb = combination str(root.val)
            if not root.left and not root.right:
                bin.append(newComb) #array is accessible
            ...

CodePudding user response:

It's because you change the object that ans represents but the object that bin represents does not change. If you modified the second piece of code to bin = bin [newComb] you would get the same error.

You can add nonlocal ans to the top of the first DFS function to let the interpreter know that you intend to change the value of ans outside the current scope

  • Related