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