Skip to content

Visualizers

Binary Search Tree Visualizer

Interactive BST displaying insertion, deletion, and searching.

native (SVG) Client-side
Ready. Type a number and click Insert, Delete or Search.

Execution Log

Tree Height: 0
Total Nodes: 0
Current Action:

Idle

Legend:

Standard Node
Active Traversal Path
Target Found / Inserted

Binary Search Tree (BST) Operations

A Binary Search Tree is a node-based binary tree data structure where each node has at most two children. It keeps its keys in sorted order, which allows for fast lookups, additions, and deletions.

BST Properties

For any given node in a BST:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • The left and right subtrees must each also be a binary search tree.

Implementation

class Node {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

class BST {
  constructor() {
    this.root = null;
  }

  insert(val) {
    this.root = this._insert(this.root, val);
  }
  _insert(node, val) {
    if (!node) return new Node(val);
    if (val < node.val) node.left = this._insert(node.left, val);
    else if (val > node.val) node.right = this._insert(node.right, val);
    return node;
  }

  search(val) {
    return this._search(this.root, val);
  }
  _search(node, val) {
    if (!node || node.val === val) return node;
    if (val < node.val) return this._search(node.left, val);
    return this._search(node.right, val);
  }
}