SDE & MLE Prep

98. Validate Binary Search Tree

Problem

Decide whether a binary tree is a valid binary search tree: for every node, all values in its left subtree are strictly smaller and all values in its right subtree strictly larger.

Example: [2,1,3] → true; [5,1,4,null,null,3,6] → false (3 sits in 5's right subtree)

Constraints: values span the full 32-bit range.

Each node must lie strictly within (lo, hi) inherited from ancestors — checking only direct children is the classic bug.

      5            (−∞, ∞)
    1   6          1:(−∞,5)  6:(5,∞)
       3  7        3:(5,6)  ✗  3 < 5

Complexity: O(n).

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        def ok(node, lo, hi):
            if not node:
                return True
            if not lo < node.val < hi:
                return False
            return ok(node.left, lo, node.val) and ok(node.right, node.val, hi)

        return ok(root, float("-inf"), float("inf"))