AlgoTales · Roadmap

Validate BST

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Validating a binary search tree checks that every node really obeys the rule: everything on its left is smaller and everything on its right is bigger, all the way down. Checking only a node and its direct children is not enough, as a hidden bug can sit further below.

Practical use cases

  • Web app: Catching a corrupted index in tests. A team stores ranked results in a custom search tree. After a refactor, some scores land on the wrong side and lookups silently miss. A validation check run in the test suite spots the first value that breaks its allowed range, so the bug is caught before release.
  • Web app: Checking imported data before trusting it. An admin uploads a file that is supposed to contain a sorted structure of price tiers. Before loading it, the importer validates the ordering rule and rejects the file with a clear message. Wrong prices never reach the shop. Support gets fewer angry emails.
  • System: Debug assertions and data integrity. Databases and libraries run internal consistency checks that confirm their ordered structures are still correct after crashes or risky changes. If a check fails, the library stops early instead of returning wrong answers later. Developers also switch such checks on while testing their own code.

The story: The Sneaky Ledger

Raju's ledger tree had served him well for months. One morning a customer complained, "Raju bhaiya, my account vanished!" Raju searched the usual way, but the account was nowhere to be found, even though he was sure it was there. Someone had tampered with the ledger.

Mira offered to inspect it. At first she only compared every card with its two children: smaller on the left, bigger on the right. Everything checked out! Yet the search still failed. Then she found the sneaky mistake: a card 9 was hiding in the left half under the top card 8. The card 9 was bigger than its parent 6, so the parent-and-child check passed, but 9 should never be on the left of 8.

Mira changed her method. As she walked down, she carried a little window of allowed numbers. At the top, anything is allowed. Going left, the window's upper limit becomes the parent's number; going right, the lower limit becomes the parent's number. A card outside its window means the tree is not a real BST. This is how we validate a BST.

How to spot this problem, and where you need it

You suspect that an ordered tree has quietly gone wrong, for example lookups fail even though the data is there, and you need a reliable way to prove it is valid or find the bad spot.

Signs you need it

  • Searches return "not found" for values you know were inserted, or results come out in the wrong order.
  • You wrote a check that compares each node only with its two children, and bad trees still pass.
  • The task says "determine whether this is a valid BST".

Where to use it in a project

  • Unit tests that run after many inserts and deletes on a hand-written ordered structure.
  • Import and sync code that loads a tree from a file or another system and must not trust it blindly.

The solution

Walk the tree while carrying a lower and upper limit for each node. The root may be anything. When you go left, the current value becomes the new upper limit; when you go right, it becomes the new lower limit. If any node falls outside its limits, the tree is invalid. Alternatively, walk inorder and confirm each value is bigger than the last.

Payoff: Before: lookups that fail mysteriously in production. After: a test that names the first bad node within one pass of the tree.

Explain it like I am 8

Each room in a house has a sign: "only numbers between X and Y can live here". Every time you go through a door, the sign gets narrower. If someone lives in the wrong room, the sign gives them away.

How it works, step by step

  1. Start at the root with the window (no low limit, no high limit).
  2. Check that the node's value is inside its window. If not, it is not a BST.
  3. Go left with the window's high limit set to this node's value; go right with the low limit set to this node's value.
  4. An empty tree is valid. If every node passes, the tree is a BST. (Alternative: an inorder walk must produce strictly increasing values.)

The code in four languages

PHP

<?php
class Node {
    public ?Node $left = null;
    public ?Node $right = null;
    public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
    if ($n === null) return new Node($v);
    if ($v < $n->val) $n->left = insert($n->left, $v);
    else $n->right = insert($n->right, $v);
    return $n;
}

// Every node must stay inside the (low, high) window set by its ancestors
function isValid(?Node $n, ?int $low = null, ?int $high = null): bool {
    if ($n === null) return true;                          // empty is fine
    if ($low !== null && $n->val <= $low) return false;
    if ($high !== null && $n->val >= $high) return false;
    return isValid($n->left, $low, $n->val)                // left: new high limit
        && isValid($n->right, $n->val, $high);             // right: new low limit
}

// The tempting but WRONG check: only compares a node with its direct children
function naive(?Node $n): bool {
    if ($n === null) return true;
    if ($n->left !== null && $n->left->val >= $n->val) return false;
    if ($n->right !== null && $n->right->val <= $n->val) return false;
    return naive($n->left) && naive($n->right);
}

$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo 'good tree valid? ', isValid($root) ? 'yes' : 'no', PHP_EOL;       // yes

$root->left->right->right->val = 9;                        // sneak 9 into the left side
echo 'bad tree, naive check: ', naive($root) ? 'passes (wrong!)' : 'fails', PHP_EOL;
echo 'bad tree, window check: ', isValid($root) ? 'yes' : 'no', PHP_EOL;   // no

JavaScript

class Node {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
  if (n === null) return new Node(v);
  if (v < n.val) n.left = insert(n.left, v);
  else n.right = insert(n.right, v);
  return n;
}

// Every node must stay inside the (low, high) window set by its ancestors
function isValid(n, low = null, high = null) {
  if (n === null) return true;                             // empty is fine
  if (low !== null && n.val <= low) return false;
  if (high !== null && n.val >= high) return false;
  return isValid(n.left, low, n.val)                       // left: new high limit
      && isValid(n.right, n.val, high);                    // right: new low limit
}

// The tempting but WRONG check: only compares a node with its direct children
function naive(n) {
  if (n === null) return true;
  if (n.left !== null && n.left.val >= n.val) return false;
  if (n.right !== null && n.right.val <= n.val) return false;
  return naive(n.left) && naive(n.right);
}

let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log('good tree valid? ' + (isValid(root) ? 'yes' : 'no'));        // yes

root.left.right.right.val = 9;                             // sneak 9 into the left side
console.log('bad tree, naive check: ' + (naive(root) ? 'passes (wrong!)' : 'fails'));
console.log('bad tree, window check: ' + (isValid(root) ? 'yes' : 'no')); // no

Java

public class Main {
    static class Node {
        int val;
        Node left, right;
        Node(int val) { this.val = val; }
    }

    static Node insert(Node n, int v) {
        if (n == null) return new Node(v);
        if (v < n.val) n.left = insert(n.left, v);
        else n.right = insert(n.right, v);
        return n;
    }

    // Every node must stay inside the (low, high) window set by its ancestors (null = no limit)
    static boolean isValid(Node n, Integer low, Integer high) {
        if (n == null) return true;                            // empty is fine
        if (low != null && n.val <= low) return false;
        if (high != null && n.val >= high) return false;
        return isValid(n.left, low, n.val)                     // left: new high limit
            && isValid(n.right, n.val, high);                  // right: new low limit
    }

    // The tempting but WRONG check: only compares a node with its direct children
    static boolean naive(Node n) {
        if (n == null) return true;
        if (n.left != null && n.left.val >= n.val) return false;
        if (n.right != null && n.right.val <= n.val) return false;
        return naive(n.left) && naive(n.right);
    }

    public static void main(String[] args) {
        Node root = null;
        for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
        System.out.println("good tree valid? " + (isValid(root, null, null) ? "yes" : "no"));   // yes

        root.left.right.right.val = 9;                         // sneak 9 into the left side
        System.out.println("bad tree, naive check: " + (naive(root) ? "passes (wrong!)" : "fails"));
        System.out.println("bad tree, window check: " + (isValid(root, null, null) ? "yes" : "no"));   // no
    }
}

Go

package main

import "fmt"

type Node struct {
	val         int
	left, right *Node
}

func insert(n *Node, v int) *Node {
	if n == nil {
		return &Node{val: v}
	}
	if v < n.val {
		n.left = insert(n.left, v)
	} else {
		n.right = insert(n.right, v)
	}
	return n
}

// isValid checks that every node stays inside the (low, high) window set by
// its ancestors. A nil pointer means "no limit on that side".
func isValid(n *Node, low, high *int) bool {
	if n == nil {
		return true // empty is fine
	}
	if low != nil && n.val <= *low {
		return false
	}
	if high != nil && n.val >= *high {
		return false
	}
	return isValid(n.left, low, &n.val) && // left: new high limit
		isValid(n.right, &n.val, high) // right: new low limit
}

// naive is the tempting but WRONG check: it only compares a node with its direct children.
func naive(n *Node) bool {
	if n == nil {
		return true
	}
	if n.left != nil && n.left.val >= n.val {
		return false
	}
	if n.right != nil && n.right.val <= n.val {
		return false
	}
	return naive(n.left) && naive(n.right)
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	var root *Node
	for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
		root = insert(root, v)
	}
	fmt.Println("good tree valid?", yesNo(isValid(root, nil, nil))) // yes

	root.left.right.right.val = 9 // sneak 9 into the left side
	naiveResult := "fails"
	if naive(root) {
		naiveResult = "passes (wrong!)"
	}
	fmt.Println("bad tree, naive check:", naiveResult)
	fmt.Println("bad tree, window check:", yesNo(isValid(root, nil, nil))) // no
}

Time: O(n) · Extra space: O(h). Every node is checked once; the recursion goes as deep as the tree is tall.

Watch out for

  • Only comparing a node with its immediate children. A bad value deeper down can hide behind a correct-looking parent.
  • Using smaller-or-equal checks inconsistently with the duplicates policy. Decide whether equal values are allowed and apply it everywhere.
  • Initialising the window with a fake limit like 0 or -1000. Use "no limit" (null) so any legitimate value works.

Quick check

  1. Why is "parent vs children only" not enough?
    • It is too slow
    • A node must also respect all of its ancestors
    • It uses extra memory
  2. Going to the right child, which limit changes?
    • The high limit
    • Both limits
    • The low limit becomes the parent's value
  3. Another correct method?
    • Check that a preorder walk is sorted
    • Check that an inorder walk is strictly increasing
    • Count the leaves