Skip to content

Instantly share code, notes, and snippets.

@conste11ations
Created May 30, 2020 19:31
Show Gist options
  • Save conste11ations/3b5113c1d2c7b498c2699b454fc31b92 to your computer and use it in GitHub Desktop.
Save conste11ations/3b5113c1d2c7b498c2699b454fc31b92 to your computer and use it in GitHub Desktop.
class BinaryNode {
constructor(number) {
this.number = number;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(number) {
this.root = new BinaryNode(number);
}
insert(number) {
const newNode = new BinaryNode(number);
this.insertNode(this.root, newNode);
}
insertNode(existingNode, newNode) {
if (newNode.number <= existingNode.number) {
if (!existingNode.left) {
existingNode.left = newNode;
} else {
this.insertNode(existingNode.left, newNode);
}
} else {
if (!existingNode.right) {
existingNode.right = newNode;
} else {
this.insertNode(existingNode.right, newNode);
}
}
}
remove(number) {
this.root = this.removeNode(this.root, number)
}
removeNode(node, target) {
if (!node) {
return null;
}
if (target < node.number) {
node.left = this.removeNode(node.left, target);
}
else if (target > node.number) {
node.right = this.removeNode(node.right, target);
} else {
if (!node.left && !node.right) {
node = null;
} else if (!node.left || !node.right) {
node = node.right ? node.right : node.left
} else {
const candidate = this.findIdealReplacement(node.right);
node.number = candidate.number;
node.right = this.removeNode(node.right, candidate.number);
}
}
return node;
}
findIdealReplacement(startingNode) {
if (!startingNode.left)
return startingNode;
else
return this.findIdealReplacement(startingNode.left);
}
}
testBST = new BinarySearchTree(28)
testBST.insert(21)
testBST.insert(100)
testBST.insert(120)
testBST.insert(110)
testBST.insert(5)
testBST.insert(25)
console.log(testBST)
testBST.remove(28)
console.log(testBST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment