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 {
int value;
BSTNode left;
BSTNode right;
BSTNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
public void insert(int value) {
BSTNode newNode = new BSTNode(value);
if (root == null) {
root = newNode;
return;
}
insertNode(root, newNode);
}
private void insertNode(BSTNode node, BSTNode newNode) {
if (newNode.value < node.value) {
if (node.left == null) {
node.left = newNode;
} else {
insertNode(node.left, newNode);
}
} else {
if (node.right == null) {
node.right = newNode;
} else {
insertNode(node.right, newNode);
}
}
}
class BST {
BSTNode root;
public BST() {
this.root = null;
}
public void insert(int value) {
BSTNode newNode = new BSTNode(value);
if (root == null) {
root = newNode;
return;
}
insertNode(root, newNode);
}
private void insertNode(BSTNode node, BSTNode newNode) {
if (newNode.value < node.value) {
if (node.left == null) {
node.left = newNode;
} else {
insertNode(node.left, newNode);
}
} else {
if (node.right == null) {
node.right = newNode;
} else {
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 {
BSTNode root;
public BST() {
this.root = null;
}
// Previous methods here...
public boolean search(int value) {
return searchRecursive(root, value);
}
private boolean searchRecursive(BSTNode node, int value) {
if (node == null) {
return false;
}
if (node.value == value) {
return true;
}
if (value < node.value) {
return searchRecursive(node.left, value);
} else {
return searchRecursive(node.right, value);
}
}
}
If you want more practice with Binary Search Trees, check out these LeetCode problems: