递归 利用二叉搜索树的定义
# 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: Optional[TreeNode], lower, upper) -> bool:
if not node:
return True
# 判断当前节点是否符合 上下界
if node.val >= upper or node.val <= lower:
return False
# 当前节点的左子树的值的上界是 当前节点的值
# 更新上界 维持之前的下界
if not isValid(node.left, lower, node.val):
return False
# 当前节点的右子树的值的下界是 当前节点的值
if not isValid(node.right, node.val, upper):
return False
# 到达此处 当前节点的值符合上下界 左、右子树的值也符合各自的上下界
return True
return isValid(root, -math.inf, math.inf)
二叉搜索树的中序遍历是升序遍历
# 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:
tmpVal, stack, cur = -math.inf, [], root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
tmp = stack.pop()
# 二叉搜索树的中序遍历为升序遍历
# 进行中序遍历 和上一个节点的值进行对比即可
if tmp.val <= tmpVal:
return False
cur = tmp.right
tmpVal = tmp.val
return True