JSFiddle - React, Tailwind, and code Playground
JavaScript
console.clear();
let c = (...s) => console.log(...s)
// BST - Binary Search Tree + Traversal
class Node {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
}
class BST {
constructor() {
this.root = null;
}
// add a new node to tree
add(data) {
const node = this.root;
// if it;s first node
if (node == null) {
this.root = new Node(data);
return;
}
// search tree function(recursive) ie where to put data
let searchTree = (node) => {
// less than node.data - compare left node
if (data < node.data) {
if (node.left == null) {
node.left = new Node(data);
return;
} else {
searchTree(node.left);
return;
}
}
// more than node.data - compare right node
if (data > node.data) {
if (node.right == null) {
node.right = new Node(data);
return;
} else {
searchTree(node.right);
return;
}
}
return null; // data is either invalid or equal to node.data
}
return searchTree(node);
}
// find Min
findMin() {
let current = this.root;
while (current.left != null) {
current = current.left;
}
return current.data;
}
// find Max
findMax() {
let current = this.root;
while (current.right != null) {
current = current.right;
}
return current.data;
}
// find if input data is present
isPresent(data) {
let current = this.root;
while (current !== null) {
if (current.data == data) return true;
if (current.data > data) current = current.left;
if (current.data < data) current = current.right;
}
return false;
}
// remove node
remove(data) {
// we use a revursive function
let removeNode = (node, data) => {
if (node == null) return;
// node found
if (node.data ==...