D&C:
# 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 = rightclass Result:def __init__(self, maxval = float("-inf"), minval = float("inf"), isBST = True):self.maxval = maxvalself.minval = minvalself.isBST = Trueclass Solution:#divide and conquerdef isValidBST(self, root: TreeNode) -> bool:ans = self.helper(root)return ans.isBSTdef helper(self, root: TreeNode) -> Result:if root == None:return Result()left = self.helper(root.left)right = self.helper(root.right)result = Result()result.isBST = left.maxval < root.val < right.minval and left.isBST and right.isBSTresult.maxval = max(left.maxval, right.maxval, root.val)result.minval = min(left.minval, right.minval, root.val)return result
Inorder:
# 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 = rightclass Result:def __init__(self, maxval = float("-inf"), minval = float("inf"), isBST = True):self.maxval = maxvalself.minval = minvalself.isBST = Trueclass Solution:#InordercurrentVal = float("-inf")def isValidBST(self, root: TreeNode) -> bool:if root == None:return Trueif not (self.isValidBST(root.left)):return Falseif self.currentVal >= root.val:return Falseself.currentVal = root.valif not self.isValidBST(root.right):return Falsereturn True
