力扣题目:110. 平衡二叉树
实现1:
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root: TreeNode) -> int:
if root == None:
return 0
else:
return max(height(root.left), height(root.right)) + 1
if root == None:
return True
else:
return abs(height(root.left) - height(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
实现1中height函数是定义在isBalanced函数里面的,因此递归调用时不用加self.
实现2:
class Solution:
def height(self, root: TreeNode):
if root == None:
return 0
else:
return max(self.height(root.left), self.height(root.right)) + 1
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if root == None:
return True
else:
return abs(self.height(root.left) - self.height(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
在类中实现了成员函数height,在同级别的成员函数isBalanced中调用height时,需要加上self.
造成这种差异的原因是什么呢?