Leetcode 98 Solution

This article provides solution to leetcode question 98 (validate-binary-search-tree)



# 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:
        self.last_val = None

        return self._isValidBST(root)

    def _isValidBST(self, root: Optional[TreeNode]) -> bool:
        if root.left:
            if not self._isValidBST(root.left):
                return False

        if self.last_val is not None and root.val <= self.last_val:
            return False
        self.last_val = root.val

        if root.right:
            if not self._isValidBST(root.right):
                return False

        return True