Coding problem · Medium · Trees

Validate Binary Search Tree

Medium Algorithms & data structures Most askedSeen at Amazon, Meta, Microsoft, Bloomberg

Given the root of a binary tree, return true if it is a valid binary search tree: every node's left subtree contains only smaller values, its right subtree only larger values, and both subtrees are BSTs.

Example 1

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

Example 2

Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: 4 is in 5's right subtree but is smaller than 5.

Hints

Hint 1

Comparing a node only with its direct children is not enough.

Hint 2

Pass down an allowed (low, high) range; or check that an in-order traversal is strictly increasing.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(h)

DFS with bounds: the root may be anything; going left tightens the upper bound to the parent's value, going right tightens the lower bound. Any value outside (low, high) breaks the property. Duplicates are invalid (strict inequalities).

Reference solution

function isValidBST(root, low = -Infinity, high = Infinity) {
  if (!root) return true;
  if (root.val <= low || root.val >= high) return false;
  return isValidBST(root.left, low, root.val) && isValidBST(root.right, root.val, high);
}

Common mistakes

  • Only checking left.val < node.val < right.val misses violations deeper in the tree ([5,4,6,null,null,3,7]).