Validate Binary Search Tree

Pattern: Validate BST

medium

Pass down the open range each node must fit in: the root fits anywhere, a left child must be below its parent and above the parent's lower limit, a right child above its parent and below the parent's upper limit. Fail as soon as a value is outside its range.

The problem

Return whether the tree is a valid BST: every value in a left subtree is strictly smaller than the node and every value in a right subtree strictly larger. [2, 1, 3] is true; [5, 1, 4, null, null, 3, 6] is false. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Is checking each node against its children enough?
  • What limits does a node inherit from its ancestors?
  • What else gives the answer in one pass?

Hints

    Brute force, and why it fails

    For every node, check all values in its subtrees: O(n²).

    The key insight

    Each node's allowed range is fixed by its ancestors, so passing the range down checks the whole rule in one pass.

    Dry run

    [5, 1, 4, null, null, 3, 6]. 5 fits (-∞, ∞). 1 must be in (-∞, 5): yes.

    Step 1 of 3

    The plan

    valid(n, lo, hi): if null: true; if not lo < n.val < hi: false
      return valid(n.left, lo, n.val) and valid(n.right, n.val, hi)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One pass.

    Edge cases

    • Empty tree: true.
    • Equal values: false.
    • Values at the int limits (use 64-bit bounds).
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isValidBST(TreeNode root) {
            return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
    
        private boolean valid(TreeNode n, long lo, long hi) {   // every value must lie strictly between lo and hi
            if (n == null) return true;
            if (n.val <= lo || n.val >= hi) return false;
            return valid(n.left, lo, n.val) && valid(n.right, n.val, hi);
        }
    }

    C++

    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            return valid(root, LLONG_MIN, LLONG_MAX);
        }
    
        bool valid(TreeNode* n, long long lo, long long hi) {   // every value must lie strictly between lo and hi
            if (n == NULL) return true;
            if (n->val <= lo || n->val >= hi) return false;
            return valid(n->left, lo, n->val) && valid(n->right, n->val, hi);
        }
    };

    Python

    class Solution:
        def isValidBST(self, root) -> bool:
            def valid(n, lo, hi) -> bool:           # every value must lie strictly between lo and hi
                if n is None:
                    return True
                if not lo < n.val < hi:
                    return False
                return valid(n.left, lo, n.val) and valid(n.right, n.val, hi)
    
            return valid(root, float("-inf"), float("inf"))

    Common mistakes

    • Comparing only with the parent.
    • Using int bounds that clash with real values.

    Similar problems