JSFiddle - React, Tailwind, and code Playground
JavaScript
class Node {
constructor(data) {
this.value = data;
this.left = null;
this.right = null;
}
}
class Tree {
constructor() {
this.root = null;
this.count = 0;
}
insert(data) {
if (typeof data === "number") {
let newNode = new Node(data);
if (!this.root) {
this.root = newNode;
this.count++;
return;
}
let dft = (node) => {
// check root
if (data === node.value) {
console.log("node already exist");
return;
}
// check left
if (data < node.value) {
if (node.left) {
dft(node.left);
} else {
node.left = newNode;
this.count++;
}
}
// check right
if (data > node.value) {
if (node.right) {
dft(node.right);
} else {
node.right = newNode;
this.count++;
}
}
};
dft(this.root);
}
}
min() {
let currentNode = this.root;
while (currentNode.left) {
currentNode = currentNode.left;
}
console.log(currentNode);
return currentNode;
}
max() {
let currentNode = this.root;
while (currentNode.right) {
currentNode = currentNode.right;
}
console.log(currentNode);
return currentNode;
}
print() {
let dft = (node) => {
// check root
console.log(node.value);
// check left
if (node.left) {
dft(node.left);
}
// check right
if (node.right) {
dft(node.right);
}
};
dft(this.root);
}
size() {
console.log(this.count);
return this.count;
}
}
let t = new Tree();
t.insert(23);
t.insert(32);
t.insert(43);
t.insert(10);
t.insert(5);
t.insert(52);
t.insert(27);
t.insert(17);
t.insert(45);
t.insert(36);
t.insert(44);
/* t.min()
t.max() */
t.print()
t.size()