Typorithm · medium

Validate BST

validate-bsttreesbstboundsrecursion
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Validate BST

0%

Trees

Recurse with an open (low, high) interval; each node must fall strictly inside, tightening bounds going down.

A BST requires every node greater than all left-subtree values and less than all right-subtree values — not just its direct children.

Carry a valid (low, high) range and check each node against it.

Going left tightens the upper bound to the node's value; going right tightens the lower bound.

01

Pass a (low, high) range down.

02

Left tightens high, right tightens low.

03

Start with -Infinity and Infinity.

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

  return valid(root, -Infinity, Infinity);
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Empty is valid

An empty subtree never violates the BST rule.

if (node === null) {
      return true;
    }

2. Range check

The value must lie strictly inside the open interval.

if (node.val <= low || node.val >= high)

3. Tighten upper

Left children must be below this node's value.

valid(node.left, low, node.val)

4. Tighten lower

Right children must be above this node's value.

valid(node.right, node.val, high)

5. Open bounds

The root may be any value, so start with infinite bounds.

valid(root, -Infinity, Infinity)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Validate BST: Lesson & Practice · Typorithm | ApplyDjinn