# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @return bool布尔型 # class Solution: def dfs(self , root: TreeNode): # write code here leftb = rightb = True maxc = root.val maxleft = maxright = float("-inf") minc = root.val minleft = minright = float("inf") if root.left is not None: if root.left.val>root.val: return False, root.left.val, root.val leftb, maxleft, minleft = self.dfs(root.left) if maxleft>root.val: leftb = False if root.right is not None: if root.right.val<root.val: return False, root.val, root.right.val rightb,maxright,minright = self.dfs(root.right) if minright<root.val: rightb = False maxc = max(maxc,max(maxleft,maxright)) minc = min(minc,min(minleft,minright)) return (leftb and rightb),maxc,minc def isValidBST(self , root: TreeNode) -> bool: # write code here res,maxc,minc = self.dfs(root) return res