0

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
BigDreamz
  • 816
  • 1
  • 7
  • 9
  • 1
    You are *assigning* to `maxHeight`; that makes it a local variable by default. But you aren't assigning anything to `result`, you are just calling a method on it. – jasonharper Sep 21 '20 at 14:07
  • @jasonharper what would be the best way to get around the error for maxHeight? Is what I did with self.maxHeight the recommended way? – BigDreamz Sep 22 '20 at 01:58

0 Answers0