Delete
Intermediate · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Deleting from a binary search tree has three cases: a leaf is simply removed, a node with one child is replaced by that child, and a node with two children is replaced by its next value in order. The tree stays valid and sorted afterwards.
Practical use cases
- Web app: Removing a cancelled booking from an index. A ticket site keeps bookings ordered by time in memory. When a user cancels, the booking must disappear without leaving a gap or breaking the order. Deleting from the tree rewires only one or two links, so the schedule page is right on the next refresh.
- Web app: Deleting an expired coupon from a sorted list. A marketing admin removes expired coupons, which are stored in expiry-date order for quick lookups. Using the delete rules means the structure stays valid after each removal. Thousands of coupons can be cleaned up without rebuilding the list.
- System: Cache eviction and database indexes. Caches that drop the oldest entry and databases that remove a row from an index both need delete in an ordered structure. Self-balancing trees used inside them build on exactly these three cases. So learning them once explains a lot of database behaviour.
The story: The Cancelled Invitation
Raju's cousin's wedding had a guest list arranged as a BST by invitation number: smaller left, bigger right. Two days before the wedding came the news: three guests had cancelled. "Strike their names off the list, but keep it in order!" said Grandpa Bhaskar.
The first guest, number 1, had nobody listed under him, so he was simply crossed out. Easy. The second, number 14, had just one name below him (13). Grandpa moved 13 up into his place and the order survived. But the third was number 3, with two names under him (1 and 6). If Grandpa crossed him out, the two families would be left with no parent to hang from!
Grandpa found a neat solution: look for the next-larger guest, the smallest name in 3's right group. That was 4. He wrote 4 over 3's spot, then crossed out the old 4 (who had nobody under him, an easy case). The list stayed perfectly sorted. That is the famous three-case BST delete.
How to spot this problem, and where you need it
Items leave an ordered collection all the time, and you must remove them quickly without losing the order or breaking the tree.
Signs you need it
- Your sorted array uses array_splice() to remove items and each delete moves thousands of elements.
- Deleted rows leave holes or make search results wrong until the whole list is rebuilt.
- The statement says "delete a node from a BST" or "remove while keeping order".
Where to use it in a project
- Cancelling bookings, expiring coupons and removing sessions from time-ordered in-memory structures.
- Cleaning old entries from caches or indexes that are kept in sorted order.
The solution
First search for the node. If it has no children, remove it. If it has one child, link the node's parent straight to that child. If it has two children, find the smallest node in its right side, copy that value into the node, then delete that smaller node (which has at most one child). Order is preserved in every case.
Payoff: Before: shifting 10,000 array items per removal. After: a few link changes, roughly 15 steps, and the order is still correct.
Explain it like I am 8
Taking a bead off a necklace of buckets: if the bucket has nothing inside, just remove it. If it has one smaller bucket, slide that one up. If it holds two buckets, swap in the very next number in order, then remove that number from where it was.
How it works, step by step
- Find the node with the usual search (smaller left, bigger right).
- Case 1, no children: remove it (its parent now points to nothing).
- Case 2, one child: the parent points to that child instead.
- Case 3, two children: find the inorder successor (go right once, then left as far as you can), copy its key into the node, and then delete the successor from the right subtree (it has at most one child, so it is case 1 or 2).
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 minNode(Node $n): Node {
while ($n->left !== null) $n = $n->left;
return $n;
}
function deleteNode(?Node $n, int $key): ?Node {
if ($n === null) return null; // key not in the tree
if ($key < $n->val) {
$n->left = deleteNode($n->left, $key);
} elseif ($key > $n->val) {
$n->right = deleteNode($n->right, $key);
} else { // found the node to remove
if ($n->left === null) return $n->right; // no child, or only a right child
if ($n->right === null) return $n->left; // only a left child
$succ = minNode($n->right); // two children: smallest of right side
$n->val = $succ->val; // copy it up...
$n->right = deleteNode($n->right, $succ->val); // ...and remove it from below
}
return $n;
}
function preorder(?Node $n, array &$out): void {
if ($n === null) return;
$out[] = $n->val;
preorder($n->left, $out);
preorder($n->right, $out);
}
function build(): ?Node {
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
return $root;
}
foreach ([1, 14, 3] as $key) { // leaf, one child, two children
$root = deleteNode(build(), $key);
$out = [];
preorder($root, $out);
echo 'delete ', $key, ': ', implode(' ', $out), 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 minNode(n) {
while (n.left !== null) n = n.left;
return n;
}
function deleteNode(n, key) {
if (n === null) return null; // key not in the tree
if (key < n.val) {
n.left = deleteNode(n.left, key);
} else if (key > n.val) {
n.right = deleteNode(n.right, key);
} else { // found the node to remove
if (n.left === null) return n.right; // no child, or only a right child
if (n.right === null) return n.left; // only a left child
const succ = minNode(n.right); // two children: smallest of right side
n.val = succ.val; // copy it up...
n.right = deleteNode(n.right, succ.val); // ...and remove it from below
}
return n;
}
function preorder(n, out) {
if (n === null) return;
out.push(n.val);
preorder(n.left, out);
preorder(n.right, out);
}
function build() {
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
return root;
}
for (const key of [1, 14, 3]) { // leaf, one child, two children
const out = [];
preorder(deleteNode(build(), key), out);
console.log('delete ' + key + ': ' + out.join(' '));
}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 Node minNode(Node n) {
while (n.left != null) n = n.left;
return n;
}
static Node deleteNode(Node n, int key) {
if (n == null) return null; // key not in the tree
if (key < n.val) {
n.left = deleteNode(n.left, key);
} else if (key > n.val) {
n.right = deleteNode(n.right, key);
} else { // found the node to remove
if (n.left == null) return n.right; // no child, or only a right child
if (n.right == null) return n.left; // only a left child
Node succ = minNode(n.right); // two children: smallest of right side
n.val = succ.val; // copy it up...
n.right = deleteNode(n.right, succ.val); // ...and remove it from below
}
return n;
}
static void preorder(Node n, List<Integer> out) {
if (n == null) return;
out.add(n.val);
preorder(n.left, out);
preorder(n.right, out);
}
static Node build() {
Node root = null;
for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
return root;
}
public static void main(String[] args) {
for (int key : new int[]{1, 14, 3}) { // leaf, one child, two children
List<Integer> out = new ArrayList<>();
preorder(deleteNode(build(), key), out);
System.out.println("delete " + key + ": " + out.stream().map(String::valueOf).collect(Collectors.joining(" ")));
}
}
}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 minNode(n *Node) *Node {
for n.left != nil {
n = n.left
}
return n
}
func deleteNode(n *Node, key int) *Node {
if n == nil {
return nil // key not in the tree
}
if key < n.val {
n.left = deleteNode(n.left, key)
} else if key > n.val {
n.right = deleteNode(n.right, key)
} else { // found the node to remove
if n.left == nil {
return n.right // no child, or only a right child
}
if n.right == nil {
return n.left // only a left child
}
succ := minNode(n.right) // two children: smallest of right side
n.val = succ.val // copy it up...
n.right = deleteNode(n.right, succ.val) // ...and remove it from below
}
return n
}
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 build() *Node {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
return root
}
func main() {
for _, key := range []int{1, 14, 3} { // leaf, one child, two children
var out []string
preorder(deleteNode(build(), key), &out)
fmt.Printf("delete %d: %s\n", key, strings.Join(out, " "))
}
}Time: O(h) · Extra space: O(h). Finding the node, then finding its successor, each follow one downward path; the recursion is as deep as the tree.
Watch out for
- Handling the two-children case by simply removing the node, which orphans both subtrees.
- Copying the successor up but forgetting to delete the original successor node, leaving a duplicate.
- Not reassigning children after the recursive call (
n.left = deleteNode(...)). The parent must receive the updated subtree.
Quick check
- Which node replaces a two-child node that is being deleted (commonly)?
- Its parent
- The smallest node of its right subtree (inorder successor)
- The root
- Deleting a node with exactly one child. What happens?
- The child takes its place
- Both are removed
- The tree is rebuilt
- Deleting a leaf: what changes?
- Its parent loses that child
- All keys shift
- The root changes