530 二叉搜索树的最小绝对差
Understand Python nonlocal Keyword (Nonlocal vs Global scope)
class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
pre = None
res = float("inf")
def __getMini(root: TreeNode) -> int:
nonlocal pre #循环内部都要声明nonlocal
nonlocal res #循环内部都要声明nonlocal
if not root:
return True
__getMini(root.left)
if pre and abs(root.val- pre.val) < res:
res = abs(pre.val- root.val)
pre = root
__getMini(root.right)
return res
return __getMini(root)