Deletion Techniques
Overview of Node Deletion
Deleting nodes from a Binary Search Tree (BST) involves three primary scenarios:
- Deleting a leaf node
- Deleting a node with one child
- Deleting a node with two children
graph TD
A[Deletion Scenarios] --> B[Leaf Node]
A --> C[One Child]
A --> D[Two Children]
Scenario 1: Deleting a Leaf Node
When deleting a leaf node, simply remove the node from the tree.
private Node deleteLeafNode(Node root, int key) {
if (root == null) return null;
if (root.value == key) {
return null; // Remove leaf node
}
if (key < root.value) {
root.left = deleteLeafNode(root.left, key);
} else {
root.right = deleteLeafNode(root.right, key);
}
return root;
}
Scenario 2: Deleting Node with One Child
Replace the node with its child node.
private Node deleteNodeWithOneChild(Node root, int key) {
if (root == null) return null;
if (root.value == key) {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
}
if (key < root.value) {
root.left = deleteNodeWithOneChild(root.left, key);
} else {
root.right = deleteNodeWithOneChild(root.right, key);
}
return root;
}
Scenario 3: Deleting Node with Two Children
Find the inorder successor (minimum value in right subtree) and replace the node.
private Node deleteNodeWithTwoChildren(Node root, int key) {
if (root == null) return null;
if (key < root.value) {
root.left = deleteNodeWithTwoChildren(root.left, key);
} else if (key > root.value) {
root.right = deleteNodeWithTwoChildren(root.right, key);
} else {
// Node to delete found
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// Find inorder successor
root.value = minValue(root.right);
root.right = deleteNodeWithTwoChildren(root.right, root.value);
}
return root;
}
private int minValue(Node root) {
int minv = root.value;
while (root.left != null) {
minv = root.left.value;
root = root.left;
}
return minv;
}
Deletion Complexity
Scenario |
Time Complexity |
Space Complexity |
Leaf Node |
O(log n) |
O(1) |
One Child |
O(log n) |
O(1) |
Two Children |
O(log n) |
O(1) |
Best Practices
- Always maintain BST properties after deletion
- Handle edge cases carefully
- Use recursive approaches for clean implementation
At LabEx, we emphasize understanding these deletion techniques for robust tree manipulation.