As we've previously discussed, Binary Search Trees (BSTs) play a pivotal role in data structures, especially when aiming for efficient searching and sorting. Now, as we transition into Java, one of the most widely-used programming languages in the tech industry, we'll see that the same core concepts of BSTs apply, albeit with Java's syntax and structure.
Below is the BST implemented in Java:
package datastructures.Trees;
public class BinarySearchTree {
// Root node of the BST
Node root;
// Inner Node class to represent individual nodes
class Node {
int value; // Value stored in the node
Node left; // Reference to the left child
Node right; // Reference to the right child
// Constructor to initialize the node with its value
Node(int value) {
this.value = value;
}
}
// Method to insert a new value into the BST
public boolean insert(int value) {
// Creating a new Node with the given value
Node newNode = new Node(value);
// If the BST is empty, set the new Node as root and return true
if (root == null) {
root = newNode;
return true;
}
// Temporary node to traverse the tree
Node temp = root;
// Infinite loop until we find the right place for the new node
while (true) {
// If value already exists, insertion fails
if (newNode.value == temp.value) {
return false;
}
// If the new value is less than current node's value, go left
if (newNode.value < temp.value) {
if (temp.left == null) {
temp.left = newNode;
return true;
}
temp = temp.left;
} else {
// If the new value is greater, go right
if (temp.right == null) {
temp.right = newNode;
return true;
}
temp = temp.right;
}
}
}
// Method to check if the BST contains a specific value
public boolean contains(int value) {
Node temp = root;
// Traverse the tree until a match is found or reached a leaf node
while (temp != null) {
// Value is less than current node's value, so go left
if (value < temp.value) {
temp = temp.left;
}
// Value is greater than current node's value, so go right
else if (value > temp.value) {
temp = temp.right;
}
// A match is found
else {
return true;
}
}
// If loop exits without a match, return false
return false;
}
}
Java's object-oriented nature makes the BST implementation elegant and intuitive. The structure of our BinarySearchTree
class remains consistent with our Python version, but Java's strong-typing and class-based approach offer a slightly different perspective.
Similar to our previous discussions, understanding and implementing BSTs in Java can significantly boost your problem-solving skills and provide a deeper grasp of data structures. This familiarity will undoubtedly be beneficial, especially when diving into Java-based applications or preparing for technical interviews in Java environments.