I was practicing LeetCode and got confused on the scope of self for a solution. I thought that self is a local variable to diameterOfBinaryTree(), so the nested function height() should only be able to read self.ans and not modify it, according to LEGB scoping rule. So how can height() modify self.ans in this solution? Thanks!
P.S. I couldn't get "class Solution(object):" to format correctly so just assume that the indentation is correct.
class Solution(object):
def diameterOfBinaryTree(self, root):
self.ans = 0
def height(p):
if not p: return -1
left, right = height(p.left), height(p.right)
self.ans = max(self.ans, 2+left+right)
return 1+max(left, right)
height(root)
return self.ans
selfis not being assigned a different value. It is the attribute that is assigned a different value.