class Node {
constructor(value) {
this.value =
value;
this.left =
null;
this.right =
null;
}
}
// Define the BinarySearchTree class
class BinarySearchTree {
constructor()
{
this.root =
null;
}
// Insert a
new node with the given value
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) {
return
undefined;
}
if (value
< current.value) {
if
(current.left === null) {
current.left = newNode;
return
this;
}
current
= current.left;
} else {
if
(current.right === null) {
current.right = newNode;
return
this;
}
current
= current.right;
}
}
}
// Print the
preorder traversal of the tree
preorder() {
let result =
[];
function
traverse(node) {
result.push(node.value);
if
(node.left) traverse(node.left);
if
(node.right) traverse(node.right);
}
traverse(this.root);
return
result;
}
}
// Example usage:
const bst = new BinarySearchTree();
bst.insert(10);
bst.insert(5);
bst.insert(15);
bst.insert(3);
bst.insert(7);
bst.insert(12);
bst.insert(18);
console.log(bst.preorder());
Output:-
[10, 5, 3, 7, 15, 12, 18]
0 Comments