I was working on 109. Convert Sorted List to Binary Search Tree on leetcode, and I came across a solution that I mostly understand, aside from the use of self.
The solution:
class Solution:
def sortedListToBST(self, head):
length = 0
curr = head
while curr:
curr = curr.next
length += 1
self.head = head
def recursion(start, end):
if start > end: return None
middle = (start + end) // 2
# left
left = recursion(start, middle - 1)
# root
root = TreeNode(self.head.val)
self.head = self.head.next
root.left = left
# right
root.right = recursion(middle + 1, end)
return root
return recursion(0, length - 1)
I get confused on the use of self.head = head. I understand self is used to indicate or specify the current instance of a class, and is used to access variables of said class. My current understanding of how this is working is that self.head is being defined as a global variable (outside the scope of recursion(start,end)) that points to the object head. I don't understand why self needs to be used, and why we can't just say something like copyOfHead = head instead of self.copyOfHead = head. I'm sure I'm getting some things wrong here - can somebody help me better understand the what and why of using self. in this instance?
recursionfunction is referencing the sameselfthat its parent method declares as a parameter, i.e. it's an up-level reference. It refers to the class instance that was used to callsortedListToBST. It's not global.self.headoversome_other_headis if the value is accessed from another method, or if the user of the object somehow needs access to the value ofself.headassome_object.head. If neither is the case, you're right, there's no point. Another possibility is that the author wasn't aware ofnonlocaland decided on abusingself.as the next best thing.