Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Last active April 25, 2022 19:46
Show Gist options
  • Select an option

  • Save mustafadalga/f7daee7cd99896647c868d3b73267e36 to your computer and use it in GitHub Desktop.

Select an option

Save mustafadalga/f7daee7cd99896647c868d3b73267e36 to your computer and use it in GitHub Desktop.
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return this;
}
let current = this.root;
while (true) {
if (value < current.value) {
if (current.left) {
current = current.left;
} else {
current.left = newNode;
return this;
}
} else if (value > current.value) {
if (current.right) {
current = current.right;
} else {
current.right = newNode;
return this;
}
} else {
return this;
}
}
}
find(value) {
if (!this.root || !Number.isInteger(value)) return undefined;
let current = this.root, found = false;
while (current && !found) {
if (value < current.value) {
current = current.left;
} else if (value > current.value) {
current = current.right;
} else {
found = true;
}
}
if (!found) return undefined;
return current;
}
contains(value) {
if (!this.root || !Number.isInteger(value)) return false;
let current = this.root, found = false;
while (current && !found) {
if (value < current.value) {
current = current.left;
} else if (value > current.value) {
current = current.right;
} else {
return true;
}
}
return false;
}
breadthFirstSearch() {
if (!this.root) return;
let node = this.root;
const data = [], queue = [];
queue.push(node);
while (queue.length) {
node = queue.shift();
data.push(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return data;
}
depthFirstSearchPreOrder() {
if (!this.root) return;
let current = this.root;
const data = [];
function traverse(node) {
data.push(node.value);
if (node.left) traverse(node.left);
if (node.right) traverse(node.right);
}
traverse(current);
return data;
}
depthFirstSearchPostOrder() {
if (!this.root) return;
let current = this.root;
const data = [];
function traverse(node) {
if (node.left) traverse(node.left);
if (node.right) traverse(node.right);
data.push(node.value);
}
traverse(current);
return data;
}
depthFirstSearchInOrder() {
if (!this.root) return;
const data = [];
function traverse(node) {
if (node.left) traverse(node.left);
data.push(node.value);
if (node.right) traverse(node.right)
}
traverse(this.root);
return data;
}
}
const tree = new BinarySearchTree();
tree.insert(10);
tree.insert(6);
tree.insert(15);
tree.insert(20);
tree.insert(3);
tree.insert(8);
tree.breadthFirstSearch();
tree.depthFirstSearchPreOrder();
tree.depthFirstSearchPostOrder();
tree.depthFirstSearchInOrder();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment