Search
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Searching a binary search tree is a guessing game: compare with the current node, then go left if you are looking for something smaller or right if bigger. Each step discards a big chunk of the data, so lookups stay quick as the data grows.
Practical use cases
- Web app: Looking up a customer by ID. A support agent pastes a customer id into the admin search box. The data is kept in an ordered tree, so the code compares with the top node, goes left or right and repeats. Even with a million customers it answers in about 20 steps and the box feels instant.
- Web app: Is this username already taken?. On a signup form, the page asks the server whether a username is free as the user types. An ordered structure of existing names lets the server answer by following one path from top to bottom. Registration feels smooth even with huge numbers of accounts.
- System: Dictionaries, sets and file systems. Ordered maps and sets in programming languages answer "is this key present?" by this same walk. File systems and database indexes also use tree-shaped lookups to jump straight to the item you asked for. That is why searching a huge table with an index feels so different from searching one without.
The story: Raju's Ledger Hunt
Raju's chai stall had a long list of regular customers with their unpaid tea accounts. When someone said, "Raju bhaiya, what do I owe?", Raju used to flip through the notebook page by page. On busy mornings, the customer waited and the tea went cold.
Mira reorganised the ledger as a Binary Search Tree. Each customer card was a node. Customers with smaller numbers went to the left, bigger to the right. Now when Mr. 7 asked for his account, Raju started at the top card, 8. "Seven is smaller than eight, so go left." Next card: 3. "Seven is bigger, go right." Next: 6. "Bigger, go right." There it was: 7!
The best part: every time Raju made a choice, he threw away half of the remaining cards without even reading them. And if he reached an empty spot? That meant the customer was not in the ledger at all. This walk-down-and-compare is BST search.
How to spot this problem, and where you need it
You repeatedly ask "is this value in my data, and where?" and a straightforward loop over everything is getting slower as the data grows.
Signs you need it
- Your search function uses foreach or in_array() over a big list, and response time rises with the number of records.
- The data is already stored by key in an ordered tree or map, but you are not using that order.
- The task says "find the node with this value" in a binary search tree.
Where to use it in a project
- Existence checks such as "is this email, username or coupon already used?" over large ordered sets.
- Record lookups by id in admin panels and caches that keep data in a search tree.
The solution
Start at the top node. If its value equals the target, you are done. If the target is smaller, move to the left child; if larger, to the right child. Repeat. If you reach an empty spot, the value is not there. Every move rules out a whole branch, so you visit very few nodes.
Payoff: Before: up to 1,000,000 comparisons per lookup. After: about 20, so the box answers instantly.
Explain it like I am 8
Guess a number between 1 and 100 and I only say "higher" or "lower". Every answer lets you ignore a big chunk of numbers. A BST is the guessing game drawn as a tree: each node says "go left" or "go right".
How it works, step by step
- Start at the root.
- If the current node's key equals what you want: found.
- If what you want is smaller, go to the left child; if bigger, go to the right child.
- If you step onto an empty spot (null), the key is not in the tree.
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;
}
// Returns how many nodes we looked at, or -1 when the key is missing
function search(?Node $root, int $key): int {
$cur = $root;
$looks = 0;
while ($cur !== null) {
$looks++;
if ($key === $cur->val) return $looks; // found
$cur = $key < $cur->val ? $cur->left : $cur->right; // smaller: left, bigger: right
}
return -1; // fell off the tree
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo 'search 7: ', search($root, 7), ' looks', PHP_EOL; // 4
echo 'search 5: ', search($root, 5), PHP_EOL; // -1 (not there)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;
}
// Returns how many nodes we looked at, or -1 when the key is missing
function search(root, key) {
let cur = root;
let looks = 0;
while (cur !== null) {
looks++;
if (key === cur.val) return looks; // found
cur = key < cur.val ? cur.left : cur.right; // smaller: left, bigger: right
}
return -1; // fell off the tree
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log('search 7: ' + search(root, 7) + ' looks'); // 4
console.log('search 5: ' + search(root, 5)); // -1 (not there)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;
}
// Returns how many nodes we looked at, or -1 when the key is missing
static int search(Node root, int key) {
Node cur = root;
int looks = 0;
while (cur != null) {
looks++;
if (key == cur.val) return looks; // found
cur = key < cur.val ? cur.left : cur.right; // smaller: left, bigger: right
}
return -1; // fell off the tree
}
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("search 7: " + search(root, 7) + " looks"); // 4
System.out.println("search 5: " + search(root, 5)); // -1 (not there)
}
}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
}
// search returns how many nodes we looked at, or -1 when the key is missing.
func search(root *Node, key int) int {
cur := root
looks := 0
for cur != nil {
looks++
if key == cur.val {
return looks // found
}
if key < cur.val { // smaller: left, bigger: right
cur = cur.left
} else {
cur = cur.right
}
}
return -1 // fell off the tree
}
func main() {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
fmt.Println("search 7:", search(root, 7), "looks") // 4
fmt.Println("search 5:", search(root, 5)) // -1 (not there)
}Time: O(h) · Extra space: O(1). We follow one path from the root, so the cost is the height h: about log n for a balanced tree, but n for a stick-shaped one.
Watch out for
- Searching both sides. The BST rule tells you which single side can hold the key.
- Forgetting the "not found" case: reaching null must be handled.
- Assuming it is always fast. A badly shaped (very tall) BST is no better than a plain list.
Quick check
- Searching for 7 at node 3 (7 is bigger). Where next?
- Left child
- Right child
- Back to the root
- What does reaching an empty (null) spot mean?
- The key is not in the tree
- The tree is broken
- We must search the other side
- How many nodes did we look at to find 7?
- 9
- 2
- 4