Validate Binary Search Tree

Binary Search Tree
Medium

Approach

Diagrams

Analysis

Time

Space

class Solution:
    def isValidBST(self, root):
        def dfs(node, minSoFar, maxSoFar):
            if not node:
                return True

            if not minSoFar < node.val < maxSoFar:
                return False

            leftIsValid = dfs(node.left, minSoFar, node.val)
            rightIsValid = dfs(node.right, node.val, maxSoFar)

            return leftIsValid and rightIsValid

        return dfs(root, float('-inf'), float('inf'))

Learn

#Depth-First Search

Videos