98. 验证二叉搜索树
两种方法:
1.递归,每个节点递归时都会有一个上下界,越往下遍历节点的上下界会越来越收紧,若有不在上下界内的就返回False,最初对根节点的上下界没有,那就默认为负无穷到正无穷。
Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def func(node,maxi=float('inf'),mini=float('-inf')):
if not node:
return True
if node.val<=mini or node.val>=maxi:
return False
#mini不为默认值时,表示node有位于其左侧的祖先节点,值为mini
#maxi不为默认值时,表示node有位于其右侧的祖先节点,值为maxi
return func(node.left,node.val,mini) and func(node.right,maxi,node.val)
return func(root)
2.由于二叉搜索树的中序遍历序列为严格非降序的。中序遍历,一个全局变量保存当前节点的中序前继,每次遍历到一个节点就和他的中序前继比一下大小,大于的话就继续,否则返回False
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
global res,x
x=float('-inf')
res=True
def mid_order(node):
global res
global x
if not node:
return
mid_order(node.left)
if x>=node.val:
res=False
return
x=node.val
mid_order(node.right)
mid_order(root)
return res
进击的小🐴农