Skip to content

Instantly share code, notes, and snippets.

@d3vild06
Last active February 14, 2017 21:14
Show Gist options
  • Save d3vild06/374fb1c8532a49f22fd6383e2625b9f9 to your computer and use it in GitHub Desktop.
Save d3vild06/374fb1c8532a49f22fd6383e2625b9f9 to your computer and use it in GitHub Desktop.
Binary Search Tree (Ordered Map)
class BST {
constructor(key, value, parent) {
this.key = key || null;
this.value = value || null;
this.parent = parent || null;
this.left = null;
this.right = null;
}
insert(key, value, parent) {
if (this.key === null) {
this.key = key;
this.value = value;
}
else if (key < this.key) {
if (this.left === null) {
this.left = new BST(key, value, this);
} else {
this.left.insert(key, value);
}
}
else {
if (this.right === null) {
this.right = new BST(key, value, this);
}
else {
this.right.insert(key, value);
}
}
}
get(key) {
if (this.key === key) { return this.value }
else if (key < this.key && this.left) {
return this.left.get(key);
}
else if (key > this.key && this.right) {
return this.right.get(key);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment