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