此题看题解
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.isValidBSTHelper(root, float('-inf'), float('inf'))
def isValidBSTHelper(self, root, min_val, max_val):
if not root:
return True
if root.val <= min_val or root.val >= max_val:
return False
left_valid = self.isValidBSTHelper(root.left, min_val, root.val)
right_valid = self.isValidBSTHelper(root.right, root.val, max_val)
return left_valid and right_valid