Python, confused with self.variable

  • 0
        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 1
        if root.left is None:
            return self.minDepth(root.right) + 1
        if root.right is None:
            return self.minDepth(root.left) + 1
        self.left = self.minDepth(root.left) + 1
        self.right = self.minDepth(root.right) + 1
        return min(self.left,self.right)

    This code will give me wrong result but if I change self.left ->left and self.right ->right it will work. Can anyone please explain why that is the case?

  • 0

    self.left and self.right declare instance variables on the object. Whenever you recursively call the function it will be overwriting these two values with whatever they are assigned to in the recursion. Just use local variables to the function i.e. "left" and "right".

  • 0

    @thedrizzle43 Thanks!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.