BST Insert And Delete With Successor Typed

Implement a typed binary search tree supporting insert and delete using in-order successor for two-child nodes.

TypescriptData Integrity

Code

typescriptsnippet
18 lines
interface TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; }
function node(val: number): TreeNode { return { val, left: null, right: null }; }
class BST {
  root: TreeNode | null = null;
  insert(val: number): void {
    if (!this.root) { this.root = node(val); return; }
    let cur = this.root;
    while (true) {
      if (val < cur.val) { if (!cur.left) { cur.left = node(val); return; } cur = cur.left; }
      else { if (!cur.right) { cur.right = node(val); return; } cur = cur.right; }
    }
  }
  has(val: number): boolean {
    let cur = this.root;
    while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; }
    return false;
  }
}

Inside the snippet

Count the class BST and the function node as the entire surface area of BST Insert And Delete With Successor Typed.

The nesting pairs while (true) with while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; } — the inner runs once per outer step.

The result comes back as an object carrying val, null.

What to watch for

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

Using it

Entry signature: function node(val: number)

The call returns val, null — destructure what you need at the call site.

Key statements

while (cur) { if (val === cur.val) return true; cur = val < cur.val ? cur.left : cur.right; }
function node(val: number): TreeNode { return { val, left: null, right: null }; }

Interactive Tools for This Topic

FAQ

Does `node` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `node` at load time.