98. 验证二叉搜索树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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 __init__(self):
self.pre = None
def isValidBST(self, root: Optional[TreeNode]) -> bool:
if root==None: return True
# 中序遍历 会 有序变大。
L_result = self.isValidBST(root.left)
if self.pre!=None and self.pre.val >= root.val:
return False
self.pre = root
R_result = self.isValidBST(root.right)
return L_result and R_result