Insert
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Inserting into a binary search tree means playing the search game for the new value until you reach an empty spot, then placing it there. The tree stays ordered without moving any other item, which is why it suits data that keeps arriving.
Practical use cases
- Web app: Live leaderboard taking new scores. A quiz app adds a score the moment a player finishes. The new score is compared with the top node and sent left or right until a free spot appears. The board stays sorted with no re-sort, even with thousands of players finishing every minute.
- Web app: Adding a new product to an ordered catalogue. An admin adds a new product priced 799 to a catalogue kept in price order. The code walks down the tree comparing prices and attaches the product at the empty spot. The price-sorted listing updates instantly for the next shopper.
- System: Index maintenance in databases. When a row is added to a table, the database must also add its key into every index on that table. Tree-based indexes do this the same way: find the right spot and attach the key, keeping lookups fast. This is also why too many indexes slow down writes, since each insert touches all of them.
The story: Where Does the New Kid Sit?
A new student, roll number 5, joined Mrs. Sharma's class mid-year. The class register was a neat BST: smaller roll numbers to the left, bigger to the right. "Where do I write the new name?" Mrs. Sharma asked herself. Rewriting the whole register was out of the question.
She remembered the search trick. She started at the top card, 8. "Five is smaller, go left." At 3: "Five is bigger, go right." At 6: "Smaller, go left." At 4: "Bigger, go right." And there, where the next card would be, was an empty spot. "This is exactly where 5 would have been if it had been here all along. I will put it right here."
Nothing else moved. No card was shifted, no page rewritten. The new student was just hung on the tree as a new leaf. Inserting into a BST is search plus one small last step: link a new node into the empty spot where the search ended.
How to spot this problem, and where you need it
New data keeps arriving and must be placed so that the collection stays searchable and ordered, without paying for a full sort every time.
Signs you need it
- Your code does array_push() followed by sort() after every new record, and slows down as the list grows.
- Items arrive one at a time (scores, bookings, prices) and the app must always show them in order.
- The problem says "insert a value into a binary search tree".
Where to use it in a project
- Live leaderboards and ranked lists that update as results come in.
- In-memory ordered indexes of orders, prices or timestamps added throughout the day.
The solution
Begin at the top. If the tree is empty, the new value becomes the top node. Otherwise compare: smaller goes left, bigger goes right. Keep moving to the next child. The moment you find an empty child spot, create a new node there. Nothing else has to move.
Payoff: Before: re-sorting 50,000 scores per new result. After: about 16 comparisons and one new node per result.
Explain it like I am 8
Imagine a "guess my number" game tree. To add a new number, you play the game as if you were looking for it. When you finally hit a blank spot where the answer should be, you write the number there.
How it works, step by step
- If the tree is empty, the new key becomes the root.
- Otherwise search for the key: smaller goes left, bigger goes right.
- When you arrive at a missing child (empty spot), create a new node and attach it there.
- Existing nodes do not move. Decide what to do with equal keys (reject it, or send it consistently to one side).
The code in four languages
PHP
<?php
class Node {
public ?Node $left = null;
public ?Node $right = null;
public function __construct(public int $val) {}
}
// Walk down; attach the new node at the first empty spot
function insert(?Node $root, int $v): Node {
$new = new Node($v);
if ($root === null) return $new; // empty tree: new root
$cur = $root;
while (true) {
if ($v < $cur->val) {
if ($cur->left === null) { $cur->left = $new; break; }
$cur = $cur->left;
} else { // equal keys go right in this version
if ($cur->right === null) { $cur->right = $new; break; }
$cur = $cur->right;
}
}
return $root;
}
function preorder(?Node $n, array &$out): void {
if ($n === null) return;
$out[] = $n->val;
preorder($n->left, $out);
preorder($n->right, $out);
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
$root = insert($root, 5); // the new kid: goes under 4, on the right
$out = [];
preorder($root, $out);
echo implode(' ', $out), PHP_EOL; // 8 3 1 6 4 5 7 10 14 13JavaScript
class Node {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
// Walk down; attach the new node at the first empty spot
function insert(root, v) {
const node = new Node(v);
if (root === null) return node; // empty tree: new root
let cur = root;
while (true) {
if (v < cur.val) {
if (cur.left === null) { cur.left = node; break; }
cur = cur.left;
} else { // equal keys go right in this version
if (cur.right === null) { cur.right = node; break; }
cur = cur.right;
}
}
return root;
}
function preorder(n, out) {
if (n === null) return;
out.push(n.val);
preorder(n.left, out);
preorder(n.right, out);
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
root = insert(root, 5); // the new kid: goes under 4, on the right
const out = [];
preorder(root, out);
console.log(out.join(' ')); // 8 3 1 6 4 5 7 10 14 13Java
import java.util.*;
import java.util.stream.*;
public class Main {
static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
// Walk down; attach the new node at the first empty spot
static Node insert(Node root, int v) {
Node node = new Node(v);
if (root == null) return node; // empty tree: new root
Node cur = root;
while (true) {
if (v < cur.val) {
if (cur.left == null) { cur.left = node; break; }
cur = cur.left;
} else { // equal keys go right in this version
if (cur.right == null) { cur.right = node; break; }
cur = cur.right;
}
}
return root;
}
static void preorder(Node n, List<Integer> out) {
if (n == null) return;
out.add(n.val);
preorder(n.left, out);
preorder(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);
root = insert(root, 5); // the new kid: goes under 4, on the right
List<Integer> out = new ArrayList<>();
preorder(root, out);
System.out.println(out.stream().map(String::valueOf).collect(Collectors.joining(" "))); // 8 3 1 6 4 5 7 10 14 13
}
}Go
package main
import (
"fmt"
"strings"
)
type Node struct {
val int
left, right *Node
}
// insert walks down and attaches the new node at the first empty spot.
func insert(root *Node, v int) *Node {
node := &Node{val: v}
if root == nil {
return node // empty tree: new root
}
cur := root
for {
if v < cur.val {
if cur.left == nil {
cur.left = node
break
}
cur = cur.left
} else { // equal keys go right in this version
if cur.right == nil {
cur.right = node
break
}
cur = cur.right
}
}
return root
}
func preorder(n *Node, out *[]string) {
if n == nil {
return
}
*out = append(*out, fmt.Sprint(n.val))
preorder(n.left, out)
preorder(n.right, out)
}
func main() {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
root = insert(root, 5) // the new kid: goes under 4, on the right
var out []string
preorder(root, &out)
fmt.Println(strings.Join(out, " ")) // 8 3 1 6 4 5 7 10 14 13
}Time: O(h) · Extra space: O(1). One walk down the height h of the tree, then one link. Iterative insertion needs no extra memory.
Watch out for
- Forgetting to return the (possibly new) root when inserting into an empty tree.
- Changing links of existing nodes. A BST insert only adds a new leaf; nothing else moves.
- Not deciding what to do with duplicates, then getting different behaviour in different places.
Quick check
- Where does a new key always end up in a BST insert?
- At the root
- As a new leaf at an empty spot
- In the middle of the tree
- Inserting 13 into our tree. Which path?
- 8, 3, 6
- 8, 10, 14, then left of 14
- 8, 10, then left of 10
- Inserting into an empty tree makes the new node the...
- Leaf only
- Left child
- Root