Skip to content

Latest commit

 

History

History
37 lines (31 loc) · 1002 Bytes

98. Validate Binary Search Tree.md

File metadata and controls

37 lines (31 loc) · 1002 Bytes

98. Validate Binary Search Tree (Medium)

[tag] bst, recursion

Algorithm: Top-down

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        def dfs(cur, small, large):
            if not cur:
                return True
            if not (small < cur.val < large):
                return False
            else:
                return dfs(cur.left, small, cur.val) and dfs(cur.right, cur.val, large)
        
        return dfs(root, float('-inf'), float('inf'))
        

in-order Traversal

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        
        def inorder(cur):
            if not cur:
                return True
            if not inorder(cur.left):
                return False
            if self.prev and self.prev.val >= cur.val:
                return False
            self.prev = cur
            return inorder(cur.right)
        
        self.prev = None
        return inorder(root)