Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Created March 21, 2020 16:58
Show Gist options
  • Save voidnerd/c894e1127191724e93db0c7e1bf9ec1c to your computer and use it in GitHub Desktop.
Save voidnerd/c894e1127191724e93db0c7e1bf9ec1c to your computer and use it in GitHub Desktop.
class Node {
constructor(data, left = null, right = null) {
this.left = left;
this.right = right;
this.data = data;
}
}
class BST {
constructor() {
this.root = null;
}
insert(data) {
const node = this.root;
if (node == null) {
this.root = new Node(data);
return;
} else {
const searchTree = function(node) {
if (data < node.data) {
if (node.left == null) {
node.left = new Node(data);
return;
} else if (node.left !== null) {
return searchTree(node.left);
}
} else if (data > node.data) {
if (node.right == null) {
node.right = new Node(data);
return;
} else if (node.right != null) {
return searchTree(node.right);
}
} else {
return null;
}
};
return searchTree(node);
}
}
findMin() {
let current = this.root;
while (current.left != null) {
current = current.left;
}
return current.data;
}
findMax() {
let current = this.root;
while (current.right != null) {
current = current.right;
}
return current.data;
}
find(data) {
let current = this.root;
while (current.data != data) {
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
if (current == null) {
return null;
}
}
return current;
}
contains(data) {
let current = this.root;
while (current) {
if (current.data == data) {
return true;
}
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
}
return false;
}
remove(data) {
const removeNode = (node, data) => {
if (node == null) {
return null;
}
if (data == node.data) {
if (node.left == null && node.right == null) {
return null;
}
if (node.left == null) {
return node.right;
}
if (node.right == null) {
return node.left;
}
let tempNode = node.right;
while (tempNode.left !== null) {
tempNode = tempNode.left;
}
node.data = tempNode.data;
node.right = removeNode(node.right, tempNode.data);
return node;
} else if (data < node.data) {
node.left = removeNode(node.left, data);
return node;
} else {
node.right = removeNode(node.right, data);
return node;
}
};
this.root = removeNode(this.root, data);
}
}
let bst = new BST();
bst.insert(8);
bst.insert(2);
bst.insert(9);
// bst.insert(19);
console.log("contains:", bst.contains(9));
console.log("findMax", bst.findMax(), "FindMin", bst.findMin());
bst.remove(2);
// console.log("contains:", bst.find(2));
console.debug(bst);
// console.log("---------")
// console.log(bst.printInOrder());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment