I'm trying to write a method that counts the number of distinct elements in a BST. This is my code:
def numDistinct(root):
distinct = 0
seen = {}
def private_helper(root):
if not root: return
if root.val not in seen:
seen[root.val] = root.val
distinct += 1
private_helper(root.left)
private_helper(root.right)
private_helper(root)
return distinct
However, it gives me the error UnboundLocalError: local variable 'distinct' referenced before assignment
. I understand the error, but it seems strange to me that seen
, which has the same scope as distinct
, doesn't throw the same error (even though it's referenced inside private_helper()
before distinct
is). To test this I changed distinct
to a dict and set it up so I could still use it as a counter: distinct = {'count': 0}
. The error stopped and my method started working perfectly. What is going on here? Is there a difference in scope between different data-types?