Skip to content
Problem · Canonical Warm-Up
mediumbounds · recursion · in-orderTime · O(n)Space · O(h)

Validate Binary Search Tree

Problem statement

Statement

Given the root of a binary tree, determine whether it is a valid binary search tree. A tree is a valid BST when every node in a left subtree is strictly less than its root, every node in a right subtree is strictly greater, and both subtrees are themselves valid BSTs.

Examples

    2
   / \
  1   3
root = [2, 1, 3]
-> true

      5
     / \
    1   4
       / \
      3   6
root = [5, 1, 4, null, null, 3, 6]
-> false             (4 sits in the right subtree of 5 but 4 < 5)

     10
    /  \
   5    15
       /  \
      6    20
root = [10, 5, 15, null, null, 6, 20]
-> false             (6 < 10 yet lives in 10's right subtree; both its
                      parent-child pairs are individually legal)

root = [1]
-> true

Constraints

  • The tree holds between 1 and 10^4 nodes.
  • -2^31 <= Node.val <= 2^31 - 1, so node values can reach the limits of a 32-bit signed integer.
  • Duplicates are invalid. The ordering is strict on both sides.

What this problem is really testing

Whether you can tell a local property from a global one. The definition of a BST is written recursively in terms of parent and child, which invites the reading that checking left.val < node.val < right.val at every node is sufficient. It is not, and the third example above is the counter-example: node 6 satisfies its parent 15 perfectly well, and violates its grandparent 10. Every candidate who writes the naive check passes the first two examples and fails the third, which is why interviewers keep asking this one.

The right mental model is a corridor that narrows as you descend. The root may hold any value, so its corridor is (-inf, +inf). Step left from a node of value v and the ceiling drops to v; step right and the floor rises to v. Every ancestor contributes one wall, and a node is legal exactly when its value fits inside the corridor its whole ancestry has built. Nothing else about the tree matters. Once you see the constraint as inherited rather than local, the algorithm is a single recursion carrying two extra arguments.

There is a second, equally valid framing: the in-order traversal of a BST is strictly increasing, so validating the tree is the same as checking that a sequence is sorted. That version needs only one piece of carried state, the previously visited value, and it is the one to reach for when the follow-up asks for the k-th smallest element. Knowing both, and knowing why they are the same statement, is the answer the interviewer is hoping for.