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.
Code
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.valshort-circuits the flow with an earlyreturnwhen 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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.