1.代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def isValid(node, low, high):
if not node:
return True
if not (low < node.val < high):
return False
return (isValid(node.left, low, node.val) and
isValid(node.right, node.val, high))
return isValid(root, float('-inf'), float('inf'))
2.思路
在isValidBST内部定义了递归函数isValid,如果结点为空,则返回True,否则检查结点的值是否在规定的范围内,并递归地检查左子树和右子树。