0

I am testing a very simple python script. What the function does is not important to my question, my question is the following code somehow gives me:

File "test.py", line 13, in traverse
    if root.val > minVal and ans > root.val:
UnboundLocalError: local variable 'ans' referenced before assignment

But I do have ans defined, why does it not complain about minVal but does about ans?

class Test(object):

    def findSecondMinimumValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        minVal = root.val
        ans = float("inf")

        def traverse(root):
            if not root:
                return

            if root.val > minVal and ans > root.val:
                ans = root.val

            traverse(root.left)
            traverse(root.right)

        traverse(root)
        return ans if ans != float("inf") else -1
DavidG
  • 24,279
  • 14
  • 89
  • 82
user2002692
  • 971
  • 2
  • 17
  • 34

1 Answers1

1

Inside your function traverse you are defining a new variable ans, which has nothing to do with the ans you defined above. if you want to use the same variable put nonlocal ans at the top of your traverse function.

MegaIng
  • 7,361
  • 1
  • 22
  • 35