Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Binary Search Tree Validation

Given the root of a binary tree, determine whether it is a valid Binary Search Tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with values strictly less than the node's value.
  • The right subtree of a node contains only nodes with values strictly greater than the node's value.
  • Both the left and right subtrees must also be valid BSTs.

Note that this must hold against all ancestors, not just the immediate parent — a node several levels down in a left subtree must still be less than the root, for example.

Example 1

Input: [2, 1, 3] → Output: true.

Example 2

Input: [5, 1, 4, null, null, 3, 6]

      5
     / \
    1   4
       / \
      3   6

Output: false — the root's value is 5, but its right subtree contains a node with value 4, and 4 is not greater than 5's left child's sibling constraint... more precisely, node 4's left child 3 violates nothing locally (3 < 4), but 4 itself is less than the root's requirement that everything in the right subtree be > 5... actually the real violation is simpler: 4 < 5, but 4 is in the root's right subtree, which must be entirely > 5.

Example 3

Input: [1, 1] → Output: false — values must be strictly less than / greater than, so a duplicate value in the left or right subtree is invalid.

Constraints

  • The number of nodes is in the range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1.

Share this question

← Back to Trees practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.