Interactive LabRuns in your browser

Binary Search Tree Lab

Interactive BST visualizer with insertion, deletion, and tree traversals.

Speed:
Balanced sample tree. Insert, search or delete a key, or run a traversal.
20304050607080
Nodes: 7Height: 3Best possible height: 3
Pseudocode
1insert(node, v):
2 if node is empty: create leaf v
3 if v == node.key: duplicate, stop
4 if v < node.key: insert(node.left, v)
5 else: insert(node.right, v)

About this tool

A binary search tree (BST) keeps keys in sorted order: every key in a node’s left subtree is smaller than the node, every key in the right subtree is larger. That one rule makes search, insert and delete take time proportional to the height of the tree, and an in-order walk returns the keys sorted.

This lab animates each operation step by step. You see which comparison sends the search left or right, where a new key is attached, how the three delete cases are handled, and the order in which pre-order, in-order, post-order and level-order traversals visit the nodes.

How to use Binary Search Tree Lab

  1. Type a number and choose Insert, Search or Delete. The animation plays automatically; pause it and use the step buttons to go back and forth.
  2. Watch the highlighted node and the status line: each step says which comparison was made and why the path turned left or right.
  3. Run a traversal to see the visit order build up underneath the tree.
  4. Insert keys in sorted order (1, 2, 3, 4, …) to see the tree degrade into a linked list, then compare with the AVL tree lab.

Examples

Search path

Input
Tree from 50, 30, 70, 20, 40, 60, 80 — search 60
Result
50 → right → 70 → left → 60 (found in 3 comparisons)

Delete a node with two children

Input
Delete 50 from the tree above
Result
50 is replaced by its in-order successor 60, then 60 is removed from the right subtree

Using the in-order predecessor (the largest key on the left) is equally valid.

Traversals

Input
Same tree
Result
In-order: 20 30 40 50 60 70 80 · Pre-order: 50 30 20 40 70 60 80 · Level-order: 50 30 70 20 40 60 80

Implementation in five languages

The same algorithm in Python, JavaScript, Java, Go and C++. Each program is complete and runnable; the comments show what it prints.

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
    return root  # duplicates are ignored


def search(root, key):
    while root is not None and root.key != key:
        root = root.left if key < root.key else root.right
    return root is not None


def delete(root, key):
    if root is None:
        return None
    if key < root.key:
        root.left = delete(root.left, key)
    elif key > root.key:
        root.right = delete(root.right, key)
    else:
        if root.left is None:
            return root.right
        if root.right is None:
            return root.left
        # Two children: copy the in-order successor, then delete it.
        succ = root.right
        while succ.left is not None:
            succ = succ.left
        root.key = succ.key
        root.right = delete(root.right, succ.key)
    return root


def inorder(root, out):
    if root is not None:
        inorder(root.left, out)
        out.append(root.key)
        inorder(root.right, out)
    return out


root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, k)
print(inorder(root, []))   # [20, 30, 40, 50, 60, 70, 80]
print(search(root, 60))    # True
root = delete(root, 30)
print(inorder(root, []))   # [20, 40, 50, 60, 70, 80]
class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
  }
}

function insert(root, key) {
  if (root === null) return new Node(key);
  if (key < root.key) root.left = insert(root.left, key);
  else if (key > root.key) root.right = insert(root.right, key);
  return root; // duplicates are ignored
}

function search(root, key) {
  while (root !== null && root.key !== key) {
    root = key < root.key ? root.left : root.right;
  }
  return root !== null;
}

function remove(root, key) {
  if (root === null) return null;
  if (key < root.key) root.left = remove(root.left, key);
  else if (key > root.key) root.right = remove(root.right, key);
  else {
    if (root.left === null) return root.right;
    if (root.right === null) return root.left;
    // Two children: copy the in-order successor, then delete it.
    let succ = root.right;
    while (succ.left !== null) succ = succ.left;
    root.key = succ.key;
    root.right = remove(root.right, succ.key);
  }
  return root;
}

function inorder(root, out = []) {
  if (root !== null) {
    inorder(root.left, out);
    out.push(root.key);
    inorder(root.right, out);
  }
  return out;
}

let root = null;
for (const k of [50, 30, 70, 20, 40, 60, 80]) root = insert(root, k);
console.log(inorder(root).join(", ")); // 20, 30, 40, 50, 60, 70, 80
console.log(search(root, 60)); // true
root = remove(root, 30);
console.log(inorder(root).join(", ")); // 20, 40, 50, 60, 70, 80
import java.util.ArrayList;
import java.util.List;

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

    static Node insert(Node root, int key) {
        if (root == null) return new Node(key);
        if (key < root.key) root.left = insert(root.left, key);
        else if (key > root.key) root.right = insert(root.right, key);
        return root; // duplicates are ignored
    }

    static boolean search(Node root, int key) {
        while (root != null && root.key != key) {
            root = key < root.key ? root.left : root.right;
        }
        return root != null;
    }

    static Node delete(Node root, int key) {
        if (root == null) return null;
        if (key < root.key) root.left = delete(root.left, key);
        else if (key > root.key) root.right = delete(root.right, key);
        else {
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            // Two children: copy the in-order successor, then delete it.
            Node succ = root.right;
            while (succ.left != null) succ = succ.left;
            root.key = succ.key;
            root.right = delete(root.right, succ.key);
        }
        return root;
    }

    static void inorder(Node root, List<Integer> out) {
        if (root == null) return;
        inorder(root.left, out);
        out.add(root.key);
        inorder(root.right, out);
    }

    public static void main(String[] args) {
        Node root = null;
        for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) root = insert(root, k);
        List<Integer> keys = new ArrayList<>();
        inorder(root, keys);
        System.out.println(keys);              // [20, 30, 40, 50, 60, 70, 80]
        System.out.println(search(root, 60));  // true
        root = delete(root, 30);
        keys.clear();
        inorder(root, keys);
        System.out.println(keys);              // [20, 40, 50, 60, 70, 80]
    }
}
package main

import "fmt"

type Node struct {
	Key         int
	Left, Right *Node
}

func insert(root *Node, key int) *Node {
	if root == nil {
		return &Node{Key: key}
	}
	if key < root.Key {
		root.Left = insert(root.Left, key)
	} else if key > root.Key {
		root.Right = insert(root.Right, key)
	}
	return root // duplicates are ignored
}

func search(root *Node, key int) bool {
	for root != nil && root.Key != key {
		if key < root.Key {
			root = root.Left
		} else {
			root = root.Right
		}
	}
	return root != nil
}

func remove(root *Node, key int) *Node {
	if root == nil {
		return nil
	}
	switch {
	case key < root.Key:
		root.Left = remove(root.Left, key)
	case key > root.Key:
		root.Right = remove(root.Right, key)
	default:
		if root.Left == nil {
			return root.Right
		}
		if root.Right == nil {
			return root.Left
		}
		// Two children: copy the in-order successor, then delete it.
		succ := root.Right
		for succ.Left != nil {
			succ = succ.Left
		}
		root.Key = succ.Key
		root.Right = remove(root.Right, succ.Key)
	}
	return root
}

func inorder(root *Node, out []int) []int {
	if root == nil {
		return out
	}
	out = inorder(root.Left, out)
	out = append(out, root.Key)
	return inorder(root.Right, out)
}

func main() {
	var root *Node
	for _, k := range []int{50, 30, 70, 20, 40, 60, 80} {
		root = insert(root, k)
	}
	fmt.Println(inorder(root, nil)) // [20 30 40 50 60 70 80]
	fmt.Println(search(root, 60))   // true
	root = remove(root, 30)
	fmt.Println(inorder(root, nil)) // [20 40 50 60 70 80]
}
#include <iostream>
#include <memory>
#include <vector>

struct Node {
    int key;
    std::unique_ptr<Node> left, right;
    explicit Node(int k) : key(k) {}
};

void insert(std::unique_ptr<Node>& root, int key) {
    if (!root) { root = std::make_unique<Node>(key); return; }
    if (key < root->key) insert(root->left, key);
    else if (key > root->key) insert(root->right, key);
    // duplicates are ignored
}

bool search(const Node* root, int key) {
    while (root && root->key != key) {
        root = key < root->key ? root->left.get() : root->right.get();
    }
    return root != nullptr;
}

void remove(std::unique_ptr<Node>& root, int key) {
    if (!root) return;
    if (key < root->key) remove(root->left, key);
    else if (key > root->key) remove(root->right, key);
    else if (!root->left) root = std::move(root->right);
    else if (!root->right) root = std::move(root->left);
    else {
        // Two children: copy the in-order successor, then delete it.
        Node* succ = root->right.get();
        while (succ->left) succ = succ->left.get();
        root->key = succ->key;
        remove(root->right, succ->key);
    }
}

void inorder(const Node* root, std::vector<int>& out) {
    if (!root) return;
    inorder(root->left.get(), out);
    out.push_back(root->key);
    inorder(root->right.get(), out);
}

void print(const std::unique_ptr<Node>& root) {
    std::vector<int> keys;
    inorder(root.get(), keys);
    for (int k : keys) std::cout << k << ' ';
    std::cout << '\n';
}

int main() {
    std::unique_ptr<Node> root;
    for (int k : {50, 30, 70, 20, 40, 60, 80}) insert(root, k);
    print(root);                                              // 20 30 40 50 60 70 80
    std::cout << std::boolalpha << search(root.get(), 60) << '\n'; // true
    remove(root, 30);
    print(root);                                              // 20 40 50 60 70 80
}

Practice on LeetCode

Classic problems that use this algorithm. Try them after working through the lab. Links open on LeetCode.

The three delete cases

  • Leaf: simply remove it.
  • One child: replace the node with its only child.
  • Two children: copy the in-order successor (smallest key in the right subtree) into the node, then delete the successor, which has at most one child.

Why height matters

All operations follow a single root-to-leaf path, so they cost O(h). With random insert order the expected height is about 2.99·log₂ n, but sorted input gives h = n and every operation becomes linear. Self-balancing trees such as AVL and red-black trees add rotations to keep h = O(log n).

Frequently asked questions

Everything you need to know about this tool and data security.

How are duplicate keys handled?

This lab ignores a key that already exists. Real implementations either reject duplicates, keep a count in the node, or consistently send equal keys to one side.

Which traversal should I use?

In-order for sorted output, pre-order to copy or serialize a tree, post-order to free or evaluate children before parents (e.g. expression trees), and level-order for breadth-first processing.

Is a BST the same as a binary heap?

No. A heap only guarantees that parents are bigger (or smaller) than children; it cannot search efficiently. A BST orders left and right subtrees and supports ordered queries.

Is my data safe when using this tool?

Yes, 100% safe. This tool operates entirely inside your web browser using client-side JavaScript and WebAssembly. Your data never touches any external server.