why is there only a referenced before assignment error for int values but not lists inside a nested function?

33 views Asked by At

I'm doing a leetcode problem - rightSideView. When I create an inner helper function, I thought I'd have access to the outer function variables. However, that only holds true for result (a list) but not maxHeight (an int). Code referenced below:

class Solution(object):
    def rightSideView(self, root):
       result = []
       maxHeight = 0
       def dfs(node, height):
           if node is not None:
               height += 1
               if height > maxHeight:
                   maxHeight = height
                   result.append(node.val)
               dfs(node.right, height)
               dfs(node.left, height)
       dfs(root, 0)
       return result

This can be fixed if I reference self.maxHeight; however I don't have to do the same for result. Why is this? Could it be that lists are created as global variables inside classes in python? Not sure how else to explain this.

The following code works without errors:

class Solution(object):
    def rightSideView(self, root):
       result = []
       self.maxHeight = 0
       def dfs(node, height):
           if node is not None:
               height += 1
               if height > self.maxHeight:
                   self.maxHeight = height
                   result.append(node.val)
               dfs(node.right, height)
               dfs(node.left, height)
       dfs(root, 0)
       return result
0

There are 0 answers