Validate Binary Search Tree

medium

Given the root of a binary tree, return true if it 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 are strictly larger.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Comparing a node only to its children is not enough — the property spans whole subtrees.
A valid BST's inorder traversal is strictly increasing.
Or carry a (low, high) range down: each node must satisfy low < val < high.

Common doubts

A node deep in a subtree can satisfy its parent yet still violate an ancestor's bound — e.g. a small value in a far-right subtree.
Strict — a valid BST has distinct values, so equal neighbours in inorder make it invalid.
Going left, the current node becomes the new upper bound; going right, it becomes the new lower bound.

Interview follow-ups

A postorder pass returning (min, max, size, isBST) per subtree, combining children.
You can, but the range-passing or inorder approach avoids recomputing subtree extremes at every node.

Fun facts

  • The inorder-must-increase check is why 'kth smallest' and 'validate' feel like the same problem.
  • The bounds method generalizes to interval trees and range-constrained validations.

Asked at

AmazonMicrosoftFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [2, 1, 3]
Output: true
1 < 2 < 3 — a valid BST.
Example 2
Input: root = [5, 1, 4, null, null, 3, 6]
Output: false
4 is in the right subtree of 5 but 4 < 5, violating the BST property.
Constraints

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

Solve this problem →