0

I have been doing Leetcode and I came across one issue. Its a program which finds the max Diameter of a Binary Tree. I have a class which has a nested function in it. For the class : diameterOfBinaryTree(obj), I have declared a Global variable for function: dfs(), global variable named 'dia' of type Int. When I try to access it inside dfs(), it throws me Unbound local error "UnboundLocalError: local variable 'dia' referenced before assignment"

But, when I change the variable to list and use the 0th index for the same computation, it works fine. Below is the code for functionality with Int variable

class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        dia=0
        def dfs(root): 
            print(dia)   
            if not root:
                return -1
            left=dfs(root.left)
            right=dfs(root.right)
            dia=max(dia,2+left+right)
            return 1+ max(left, right)
        
        dfs(root)
        return dia
        

This is the code using List.

class Solution(object):
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        
        def dfs(root): 
            print(dia[0])   
            if not root:
                return -1
            left=dfs(root.left)
            right=dfs(root.right)
            dia[0]=max(dia[0],2+left+right)
            return 1+ max(left, right)
        dia=[0]
        dfs(root)
        return dia[0]

The 2nd code works but the first doesnt. The same approach works for list but not for variables. Am I missing anything?

  • Please provide the other code necessary to test this. – Scott Hunter Dec 28 '22 at 19:37
  • Neither of these throw any errors. Indeed you simply define a class in both and never use it. Please don't be lazy and always provide a **complete example"*. And in neither case are the variables global. – juanpa.arrivillaga Dec 28 '22 at 19:43
  • Anyway, you are missing how local variables work in Python. **Any** assignment to a variable marks the variable as local *at compile time*. Since you try to refer to that variable earlier in the function, the interpreter doesn't find any and raises that error. In the other case, you never assign to the variable, you only access it, so it is resolved to the variable in the enclosing function. It is critical to understand, the **types of object involved are completely irrelevant** – juanpa.arrivillaga Dec 28 '22 at 19:49

1 Answers1

1

The first example does not work because you're assigning the dia variable inside of a function:

dia=max(dia,2+left+right)

And anytime you assign to a variable inside of a function, Python assumes that variable is local, even if there is a global/nonlocal variable of the same name.

But in the second example, you don't assign to the dia variable, you assign to one of its elements:

dia[0]=max(dia[0],2+left+right)

And since you don't assign to the variable, it uses the nonlocal one.

John Gordon
  • 29,573
  • 7
  • 33
  • 58