Skip to content

Instantly share code, notes, and snippets.

@markmur
Last active June 10, 2019 21:40
Show Gist options
  • Save markmur/fe40b6ecdd4c6e0dcc02bfe30e1e07b0 to your computer and use it in GitHub Desktop.
Save markmur/fe40b6ecdd4c6e0dcc02bfe30e1e07b0 to your computer and use it in GitHub Desktop.
Binary Search Tree Implementation
class Node {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
_addNode(node, value) {
if (value < node.value) {
if (!node.left) return (node.left = new Node(value));
return this._addNode(node.left, value);
} else if (value > node.value) {
if (!node.right) return (node.right = new Node(value));
return this._addNode(node.right, value);
}
}
insert(value) {
const node = this.root;
if (!node) {
this.root = new Node(value);
return this.root;
}
return this._addNode(node, value);
}
_findNode(node, value) {
if (node.value === value) return node;
if (value < node.value) return this._findNode(node.left, value);
if (value > node.value) return this._findNode(node.right, value);
}
get(value) {
if (!this.root) return;
if (this.root.value === value) return this.root;
return this._findNode(this.root, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment