Skip to problem
←

Validate Binary Search Tree

Medium 0 attempts

You're given the root of a binary tree. Determine whether it satisfies the binary search tree property: every node's value must be strictly greater than all values in its left subtree and strictly less than all values in its right subtree, not merely compared against its immediate children.

Values must be strictly ordered, so duplicate values are not allowed anywhere in a valid BST. Return a boolean.

The editor passes root as a node object with val, left, and right properties. Example arrays are level-order representations; null marks a missing child.

Function contract

Implement isValidBST(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return true if the entire tree satisfies strict binary search tree ordering; otherwise return false.

Example 1

Input
root = [2,1,3]
Output
true

Example 2

Input
root = [5,1,4,null,null,3,6]
Output
false
Visual Aid
Check every ancestor, not just the parent
105156206 is in the right subtree of 10, but 6 < 10

Node 6 is smaller than its parent 15, yet violates the lower bound inherited from 10. This tree must return false.

Constraints
  • 1 <= number of nodes <= 10^4
  • -2^31 <= Node.val <= 2^31 - 1

Iterative bound checking

Carry strict lower and upper bounds through an explicit stack. A child must satisfy every inherited ancestor bound, not just its parent comparison. Reject values equal to a bound as well as values outside it.

The initial bounds are infinities so the smallest and largest allowed integers remain valid. An explicit stack avoids JavaScript call-stack limits on a deeply skewed tree.

javascript
function isValidBST(root) {
  const stack = root ? [[root, -Infinity, Infinity]] : [];
  while (stack.length) {
    const [node, lower, upper] = stack.pop();
    if (node.val <= lower || node.val >= upper) return false;
    if (node.left) stack.push([node.left, lower, node.val]);
    if (node.right) stack.push([node.right, node.val, upper]);
  }
  return true;
}

Time: O(n), visiting each node at most once.

Space: O(h), where h is tree height; O(n) is a safe worst-case bound.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript