All examples

Binary search tree (class), .

An OOP BST - insert builds the tree, inorder walks it sorted.

binary-search-tree.js
class TreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}
class BST {
  constructor() { this.root = null; }
  insert(value) {
    const node = new TreeNode(value);
    if (this.root === null) { this.root = node; return; }
    let cur = this.root;
    while (true) {
      if (value < cur.value) {
        if (cur.left === null) { cur.left = node; return; }
        cur = cur.left;
      } else {
        if (cur.right === null) { cur.right = node; return; }
        cur = cur.right;
      }
    }
  }
  inorder(node, out) {
    if (node === null) return out;
    this.inorder(node.left, out);
    out.push(node.value);
    this.inorder(node.right, out);
    return out;
  }
}
const tree = new BST();
[5, 3, 8, 1, 4, 7, 9].forEach((v) => tree.insert(v));
tree.inorder(tree.root, []);

What to watch

Instances render as a binary tree (TreeNode left/right); the call stack shows recursive inorder traversal returning the sorted order.

Reading binary search tree (class)on a page only gets you so far - code is a process, and the process happens at runtime where you can't normally see it. In NeonFlow, this exact program runs step by step: every call opens a frame, every branch picks a path, and every value moves through memory in front of you. That's the fastest way to actually understand how binary search tree (class) works.

Run binary search tree (class) yourself

Open NeonFlow, paste this code (or any of your own), and scrub through it one step at a time.

Open NeonFlow