# 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 searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if root == None or root.val == val:
return root
if root.val>val:
result=self.searchBST(root.left,val)
return result
else:
result=self.searchBST(root.right,val)
return result
# 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:
# if root==None:
# return True
# if root.left and root.val <= root.left.val:
# return False
# if root.right and root.val >=root.right.val:
# return False
# left_bool = self.isValidBST(root.left)
# right_bool = self.isValidBST(root.right)
# index_r,index_l = root,root
# if root.right:
# index_r = root.right
# while index_r.left:
# index_r=index_r.left
# if root.left:
# index_l = root.left
# while index_l.right:
# index_l=index_l.right
# print(root.val,index_r.val,index_l.val)
# flag = True
# flag = (root.val < index_r.val or root== index_r )and (root.val >index_l.val or root== index_l)
# return left_bool and right_bool and flag
class Solution:
def __init__(self):
self.pre = None # 用来记录前一个节点
def isValidBST(self, root):
if root is None:
return True
left = self.isValidBST(root.left)
if self.pre is not None and self.pre.val >= root.val:
return False
self.pre = root # 记录前一个节点
right = self.isValidBST(root.right)
return left and right