AlgoTales · Roadmap

BST properties

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A binary search tree keeps every value smaller than a node on its left and every larger value on its right, at every level. That single rule lets you find, add and order data quickly, and it is the idea behind many database indexes.

Practical use cases

  • Web app: Autocomplete list that stays sorted. A search box suggests names while the user types. New names are added all day, and the suggestions must remain alphabetical. Keeping them in a search tree means each new name drops into its right place, so no re-sorting is needed when the list is shown.
  • Web app: Fast lookup of customers by ID. A support dashboard holds 100,000 customer records in memory. With the tree rule, each lookup goes left or right at every step and ignores half of what is left. The agent types an ID and the record appears after about 17 steps rather than 100,000.
  • System: Database indexes and sorted maps. MySQL and many other databases keep indexes in tree structures related to this one, so searching a huge table stays fast. Ordered maps and sets in many programming languages are built on trees with the same rule. So the speed you get from a built-in sorted map is this idea at work.

The story: The Street of Smaller and Bigger Houses

Grandpa Bhaskar's new colony had a funny planning rule. At every crossroad, the lane going left only had house numbers smaller than the crossroad's number, and the lane going right only had bigger numbers. And the same rule held for every smaller crossroad inside each lane.

"Why such a strict rule?" asked Mira. Grandpa grinned. "Try finding house 7. Stand at crossroad 8. Is 7 smaller? Yes, so go left. Next crossroad 3. Is 7 bigger? Yes, so go right. You never need to look at the other half of the colony."

Mira then discovered a second magic trick. If she walked through the whole colony taking the left lane first, then the crossroad itself, then the right lane, she met the house numbers in perfect sorted order. This rule, left smaller, right bigger, at every node, makes a tree a Binary Search Tree. Once you know the rule, a million houses become easy to handle.

How to spot this problem, and where you need it

You need to keep data both searchable and in order while it constantly changes, and neither a plain list (slow to search) nor a sorted list (slow to insert) is good enough.

Signs you need it

  • You search with a loop over a growing array, and the page gets slower as users add more records.
  • You keep re-sorting a list after every insert just so you can show it in order or search it.
  • The problem mentions "smaller values on the left, larger on the right" or needs "next bigger value" operations.

Where to use it in a project

  • In-memory ordered stores for leaderboards, autocomplete suggestions and sorted lookups that change often.
  • Understanding why adding an index in MySQL makes a search on a big table fast.

The solution

Store each value in a node with a left and a right link. Put smaller values in the left side and larger in the right, repeating the rule at every node. To search or add, compare with the current node and move left or right. Each step throws away a big part of the data, so work grows very slowly with size.

Payoff: Before: 100,000 checks to find one customer, and a full re-sort per insert. After: about 17 steps per search and insert, with order maintained for free.

Explain it like I am 8

A tree where every parent has a "smaller than me" bucket on the left and a "bigger than me" bucket on the right, and each bucket follows the same rule inside it. If you read the buckets left to right, everything comes out in order.

How it works, step by step

  1. Every node holds a key and has up to two children: left and right.
  2. Rule: every key in the left subtree is smaller than the node; every key in the right subtree is bigger.
  3. The rule applies to every node, not only the root, and it covers the whole subtree, not just the direct children.
  4. Bonus fact: inorder traversal (left, node, right) of a BST lists the keys in sorted order. Duplicates need a policy (for example, always go right, or do not allow them).

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;
}
function inorder(?Node $n, array &$out): void {
    if ($n === null) return;
    inorder($n->left, $out);
    $out[] = $n->val;                 // the node comes between its left and right sides
    inorder($n->right, $out);
}

$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);

$all = [];
inorder($root, $all);
echo 'inorder: ', implode(' ', $all), PHP_EOL;          // sorted!

$left = [];  inorder($root->left, $left);
$right = []; inorder($root->right, $right);
echo 'everything left of 8 is smaller: ', max($left) < $root->val ? 'yes' : 'no', PHP_EOL;
echo 'everything right of 8 is bigger: ', min($right) > $root->val ? 'yes' : 'no', PHP_EOL;

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;
}
function inorder(n, out) {
  if (n === null) return;
  inorder(n.left, out);
  out.push(n.val);                  // the node comes between its left and right sides
  inorder(n.right, out);
}

let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);

const all = [];
inorder(root, all);
console.log('inorder: ' + all.join(' '));              // sorted!

const left = [], right = [];
inorder(root.left, left);
inorder(root.right, right);
console.log('everything left of 8 is smaller: ' + (Math.max(...left) < root.val ? 'yes' : 'no'));
console.log('everything right of 8 is bigger: ' + (Math.min(...right) > root.val ? 'yes' : 'no'));

Java

import java.util.*;
import java.util.stream.*;

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;
    }

    static void inorder(Node n, List<Integer> out) {
        if (n == null) return;
        inorder(n.left, out);
        out.add(n.val);                 // the node comes between its left and right sides
        inorder(n.right, out);
    }

    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);

        List<Integer> all = new ArrayList<>();
        inorder(root, all);
        System.out.println("inorder: " + all.stream().map(String::valueOf).collect(Collectors.joining(" ")));   // sorted!

        // inorder of each side lets us check its biggest / smallest value
        List<Integer> left = new ArrayList<>(), right = new ArrayList<>();
        inorder(root.left, left);
        inorder(root.right, right);
        System.out.println("everything left of 8 is smaller: " + (Collections.max(left) < root.val ? "yes" : "no"));
        System.out.println("everything right of 8 is bigger: " + (Collections.min(right) > root.val ? "yes" : "no"));
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

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
}

func inorder(n *Node, out *[]int) {
	if n == nil {
		return
	}
	inorder(n.left, out)
	*out = append(*out, n.val) // the node comes between its left and right sides
	inorder(n.right, out)
}

func maxOf(a []int) int {
	m := a[0]
	for _, v := range a {
		if v > m {
			m = v
		}
	}
	return m
}

func minOf(a []int) int {
	m := a[0]
	for _, v := range a {
		if v < m {
			m = v
		}
	}
	return m
}

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)
	}

	var all []int
	inorder(root, &all)
	parts := make([]string, len(all))
	for i, v := range all {
		parts[i] = fmt.Sprint(v)
	}
	fmt.Println("inorder: " + strings.Join(parts, " ")) // sorted!

	// inorder of each side lets us check its biggest / smallest value
	var left, right []int
	inorder(root.left, &left)
	inorder(root.right, &right)
	fmt.Println("everything left of 8 is smaller:", yesNo(maxOf(left) < root.val))
	fmt.Println("everything right of 8 is bigger:", yesNo(minOf(right) > root.val))
}

Time: O(n) · Extra space: O(h). Listing all keys in sorted order visits every node once; the recursion is as deep as the tree is tall (h).

Watch out for

  • Thinking the rule only compares a node with its direct children. It must hold for the entire subtree: a big value hiding deep in the left side breaks the BST.
  • Forgetting a duplicates policy. Decide once whether equal keys go left, right, or are rejected, and stay consistent.
  • Assuming a BST is always short. If you insert already-sorted numbers, it becomes a long stick (more in "Balanced BST").

Quick check

  1. In a BST, where do keys smaller than a node live?
    • In its right subtree
    • In its left subtree
    • Anywhere
  2. What does an inorder walk of a BST give?
    • Keys in sorted order
    • Keys in random order
    • Only the leaves
  3. Tree: 5 with left child 3 and right child 8, and 3 has a right child 9. Is it a BST?
    • Yes, 9 is bigger than 3
    • Yes, every parent is fine
    • No, 9 is in the left subtree of 5 but is bigger than 5