辅助函数isBst携带了额外的信息帮助判断是否左节点小于根节点或右节点大于根节点
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def isBst(root, lower=float('-inf'), upper=float('inf')):
if root.val <= lower or upper <= root.val:
return False
res = True
if root.left:
res = isBst(root.left, lower, root.val)
if res and root.right:
res = isBst(root.right, root.val, upper)
return res
if not root:
return True
return isBst(root)