-2

Why do we need to use self for ans, but not min1 in the following code (via LeetCode)?

def findSecondMinimumValue(self, root):
    self.ans = float('inf')
    min1 = root.val

    def dfs(node):
        if node:
            if min1 < node.val < self.ans:
                self.ans = node.val
            elif node.val == min1:
                dfs(node.left)
                dfs(node.right)

    dfs(root)
    return self.ans if self.ans < float('inf') else -1
alan.elkin
  • 954
  • 1
  • 10
  • 19
jlin90
  • 1
  • 1

2 Answers2

1

min1 is local to the function body. Its name only exists within the body of findSecondMinimumValue(). Once your code exits that function, min1 won't be available for use.

ans is an attribute that belongs to the class instance and has to be accessed through self. If you created two different instances of whatever class this method is a part of, that would mean each instance has its own version of self.ans, self being a name that refers to the instance that calls the method and self.ans therefore referring to an instance's ans attribute.

As an example:

class Example:
    foo = "CLASS attribute"

    def __init__(self):
        self.bar = "INSTANCE attribute"
a = Example()
b = Example()
a.bar = "INSTANCE attribute changed"
print(a.bar) # -> "INSTANCE attribute changed"
print(b.bar) # -> "INSTANCE attribute" because changing a.bar doesn't affect b.bar

Example.foo = "CLASS attribute changed"
print(a.foo == b.foo) # -> True
raccoons
  • 420
  • 3
  • 16
0

I guess is much simpler. You're recursively changing self.ans. That's why, if you don't use self, you have to define and pass an extra variable, I guess.

Just another version, which'd pass through:

class Solution:
    def findSecondMinimumValue(self, root):
        self.second = float('inf')

        def traverse(node):
            if not node:
                return

            if root.val < node.val < self.second:
                self.second = node.val

            traverse(node.left)
            traverse(node.right)

        traverse(root)
        return -1 if self.second == float('inf') else self.second

References

  • For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Emma
  • 27,428
  • 11
  • 44
  • 69