Learn how to implement a Binary Search Tree insertion operation through hands-on coding. Master the fundamental technique of maintaining BST properties while adding new nodes.
class BSTNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
insert(value) {
const newNode = new BSTNode(value);
if (this.root === null) {
this.root = newNode;
return;
}
this._insertNode(this.root, newNode);
}
_insertNode(node, newNode) {
if (newNode.value < node.value) {
if (node.left === null) {
node.left = newNode;
} else {
this._insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this._insertNode(node.right, newNode);
}
}
}
class BST {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new BSTNode(value);
if (this.root === null) {
this.root = newNode;
return;
}
this._insertNode(this.root, newNode);
}
_insertNode(node, newNode) {
if (newNode.value < node.value) {
if (node.left === null) {
node.left = newNode;
} else {
this._insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this._insertNode(node.right, newNode);
}
}
}
}
Now that you've learned how to implement BST insertion, try extending your knowledge with this practice challenge.
Implement a method called search(value)
for the BST class that checks if a value exists in the tree.
true
if the value is found in the treefalse
if the value is not in the treeclass BST {
constructor() {
this.root = null;
}
// Previous methods here...
search(value) {
// Your implementation here
}
}
If you want more practice with Binary Search Trees, check out these LeetCode problems: