I’m working on implementing a Binary Search Tree (BST) in Java and need to correctly handle all cases of node deletion. The cases I need to handle are:
Node with no children (leaf node)
Node with one child
Node with two children
I’m struggling to implement the deletion method efficiently while ensuring the BST properties are maintained. Additionally, I’d like to ensure that the solution has good performance characteristics.
Here is the structure I have so far:
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public class BinarySearchTree {
private TreeNode root;
public void insert(int key) {
root = insertRec(root, key);
}
private TreeNode insertRec(TreeNode root, int key) {
if (root == null) {
root = new TreeNode(key);
return root;
}
if (key < root.val) {
root.left = insertRec(root.left, key);
} else if (key > root.val) {
root.right = insertRec(root.right, key);
}
return root;
}
// Method to delete a node from the BST
public void delete(int key) {
root = deleteRec(root, key);
}
private TreeNode deleteRec(TreeNode root, int key) {
if (root == null) {
return root;
}
if (key < root.val) {
root.left = deleteRec(root.left, key);
} else if (key > root.val) {
root.right = deleteRec(root.right, key);
} else {
// Node with only one child or no child
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
// Node with two children: Get the inorder successor (smallest in the right subtree)
root.val = minValue(root.right);
// Delete the inorder successor
root.right = deleteRec(root.right, root.val);
}
return root;
}
private int minValue(TreeNode root) {
int minVal = root.val;
while (root.left != null) {
minVal = root.left.val;
root = root.left;
}
return minVal;
}
// Method to perform in-order traversal of the BST
public void inOrder() {
inOrderRec(root);
}
private void inOrderRec(TreeNode root) {
if (root != null) {
inOrderRec(root.left);
System.out.print(root.val + " ");
inOrderRec(root.right);
}
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
// Insert nodes
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
System.out.println("Inorder traversal of the given tree:");
tree.inOrder();
System.out.println("nnDelete 20:");
tree.delete(20);
tree.inOrder();
System.out.println("nnDelete 30:");
tree.delete(30);
tree.inOrder();
System.out.println("nnDelete 50:");
tree.delete(50);
tree.inOrder();
}
Ashini Ayodhya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.