Skip to main content
31

Validate Binary Search Tree

Mediumtreesbstdfs

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TreesRead the beginner guide

Given the root of a binary tree, return true if it is a valid binary search tree (BST), and false otherwise.

Understand the problem

A BST is a binary tree where, for every node:

  • every value in its left subtree (not just its left child: everything below on the left) is strictly less than the node's value;
  • every value in its right subtree is strictly greater than the node's value.

"Strictly" means equal values aren't allowed.

Example 1

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

  2
 / \
1   3

1 < 2 < 3.

Example 2

text
Input:  root = [5, 4, 6, null, null, 3, 7]
Output: false

    5
   / \
  4   6
     / \
    3   7

Look at 6 alone and it seems fine: 3 < 6 < 7. But 3 is in 5's right subtree, so it must be greater than 5. It isn't.

Example 3

text
Input:  root = [2, 2, 2]
Output: false

Equal values break the "strictly" rule.

How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.

Constraints

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

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Pass each node an allowed range of values from its ancestors (going left lowers the ceiling, going right raises the floor), and fail as soon as a value falls outside its range.

    The trap: checking only parent and child

    The tempting solution is to check, at every node, that left.val < node.val < right.val. On Example 2 it says true:

    text
        5
       / \
      4   6
         / \
        3   7
    • At 5: 4 < 5 < 6 ✓
    • At 6: 3 < 6 < 7 ✓

    But 3 is in 5's right subtree, so it must be bigger than 5. The rule is about whole subtrees, and a local check can't see that.

    The key insight

    Each node must stay inside a range set by all of its ancestors:

    • The root can be anything: (-∞, +∞).
    • When you go left from a node with value v, everything down there must be smaller than v: the range becomes (low, v).
    • When you go right, everything must be bigger than v: the range becomes (v, high).

    The ranges get tighter as you go down, remembering every turn you took.

    Step by step

    Example 2:

    NodeAllowed rangeInside?
    5(-∞, +∞)✓
    4(-∞, 5)✓ (went left of 5)
    6(5, +∞)✓ (went right of 5)
    3(5, 6)✗ 3 is not above 5

    The answer is false.

    Another way: in-order traversal

    An in-order traversal visits the left subtree, then the node, then the right subtree. In a valid BST, this visits the values in strictly increasing order. So: traverse in order, remember the previous value, and fail if a value isn't bigger than it. The Python reference solution uses this approach, so you can see both.

    The code

    The reference solution is below, with comments on every important line (ranges in JavaScript/TypeScript, in-order in Python).

    How fast is it?

    • Time: O(n). Each node is checked once.
    • Memory: O(h) for the recursion, where h is the height.

    Common mistakes

    • Only comparing with the direct children. That's the trap above.
    • Allowing equal values. Use <= and >= for the failure check: equal is not allowed.
    • Using -2^31 and 2^31 - 1 as the starting limits. A node can hold exactly those values, and a strict check would wrongly reject it. Use -Infinity/Infinity (or None in Python).

    Going deeper

    The "pass constraints down" idea is very general: whenever the rule at a node depends on its ancestors, carry the information down as parameters. The in-order property (a BST read in order is sorted) is also the key to Kth Smallest Element in a BST.

    Reference solution

    js
    // low and high are the allowed range for this node, set by all of its ancestors.
    /**
     * @param {TreeNode | null} root
     * @return {boolean}
     */
    export default function isValidBst(root, low = -Infinity, high = Infinity) {
      // An empty tree is a valid BST.
      if (!root) return true
      // The value must be STRICTLY inside the range (equal values aren't allowed).
      if (root.val <= low || root.val >= high) return false
      // Going left: everything must be smaller than this node (new ceiling).
      // Going right: everything must be bigger than this node (new floor).
      return isValidBst(root.left, low, root.val) && isValidBst(root.right, root.val, high)
    }
    ts
    // low and high are the allowed range for this node, set by all of its ancestors.
    export default function isValidBst(
      root: TreeNode | null,
      low = -Infinity,
      high = Infinity,
    ): boolean {
      // An empty tree is a valid BST.
      if (!root) return true
      // The value must be STRICTLY inside the range (equal values aren't allowed).
      if (root.val <= low || root.val >= high) return false
      // Going left: everything must be smaller than this node (new ceiling).
      // Going right: everything must be bigger than this node (new floor).
      return isValidBst(root.left, low, root.val) && isValidBst(root.right, root.val, high)
    }
    python
    def is_valid_bst(root: TreeNode | None) -> bool:
        # In-order (left, node, right) visits a valid BST in strictly increasing order.
        previous = None  # the last value we visited
    
        def inorder(node: TreeNode | None) -> bool:
            nonlocal previous
            if node is None:
                return True
            # 1. Everything on the left first.
            if not inorder(node.left):
                return False
            # 2. This node: it must be bigger than the value just before it.
            if previous is not None and node.val <= previous:
                return False
            previous = node.val
            # 3. Then everything on the right.
            return inorder(node.right)
    
        return inorder(root)