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.
Code
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.valshort-circuits the flow with an earlyreturnwhen 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
Markdown Heading OutlineExtract ATX headings from Markdown into an indented outline with line numbers and per-level counts, ignoring code fences.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.