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;
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.