D&C:

    1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, val=0, left=None, right=None):
    4. # self.val = val
    5. # self.left = left
    6. # self.right = right
    7. class Result:
    8. def __init__(self, maxval = float("-inf"), minval = float("inf"), isBST = True):
    9. self.maxval = maxval
    10. self.minval = minval
    11. self.isBST = True
    12. class Solution:
    13. #divide and conquer
    14. def isValidBST(self, root: TreeNode) -> bool:
    15. ans = self.helper(root)
    16. return ans.isBST
    17. def helper(self, root: TreeNode) -> Result:
    18. if root == None:
    19. return Result()
    20. left = self.helper(root.left)
    21. right = self.helper(root.right)
    22. result = Result()
    23. result.isBST = left.maxval < root.val < right.minval and left.isBST and right.isBST
    24. result.maxval = max(left.maxval, right.maxval, root.val)
    25. result.minval = min(left.minval, right.minval, root.val)
    26. return result

    Inorder:

    1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, val=0, left=None, right=None):
    4. # self.val = val
    5. # self.left = left
    6. # self.right = right
    7. class Result:
    8. def __init__(self, maxval = float("-inf"), minval = float("inf"), isBST = True):
    9. self.maxval = maxval
    10. self.minval = minval
    11. self.isBST = True
    12. class Solution:
    13. #Inorder
    14. currentVal = float("-inf")
    15. def isValidBST(self, root: TreeNode) -> bool:
    16. if root == None:
    17. return True
    18. if not (self.isValidBST(root.left)):
    19. return False
    20. if self.currentVal >= root.val:
    21. return False
    22. self.currentVal = root.val
    23. if not self.isValidBST(root.right):
    24. return False
    25. return True