BST Insert And Delete With Successor (JavaScript)

Implement a binary search tree supporting insert and delete where delete uses the in-order successor for two-child nodes.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}
class BST {
  constructor() { this.root = null; }
  insert(val) {
    const node = new TreeNode(val);
    if (!this.root) { this.root = node; return; }
    let cur = this.root;
    while (true) {
      if (val < cur.val) { if (!cur.left) { cur.left = node; return; } cur = cur.left; }
      else { if (!cur.right) { cur.right = node; return; } cur = cur.right; }
    }
  }
  has(val) {
    let cur = this.root;
    while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; }
    return false;
  }
}

How it works

BST Insert And Delete With Successor (JavaScript) keeps everything in the classes TreeNode and BST.

Iteration is nested: while (true) frames the pass, while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; } does the per-item step.

What to watch for

  • The guard val === cur.val short-circuits the flow with an early return when its condition holds.

Key statements

while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; }

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install.