Binary search tree
by Saksham Malhotra
JavaScript
class Node {
constructor(value) {
this.value = value;
this.left;
this.right;
}
}
class BST {
constructor() {
this.root = null;
}
addNode(value) {
const node = new Node(value);
if (!this.root) {
this.root = node;
return;
}
let current = this.root;
while (current) {
if (value <= current.value) {
if (current.left) {
current = current.left;
} else {
current.left = node;
return;
}
} else {
if (current.right) {
current = current.right
} else {
current.right = node;
return;
}
}
}
}
printSortedTree(node = this.root) {
if (!node) {
return;
}
if (node.left) {
this.printSortedTree(node.left)
}
console.log(node.value);
if (node.right) {
this.printSortedTree(node.right)
}
}
}
const bst = new BST();
bst.addNode(4)
bst.addNode(5)
bst.addNode(1)
bst.addNode(3)
bst.printSortedTree()