Deletion in BST in Data Structures Theory - Time & Space Complexity
When deleting a node in a Binary Search Tree (BST), it is important to understand how the time taken grows as the tree size increases.
We want to know how the number of steps changes when the tree has more nodes.
Analyze the time complexity of the following deletion process in a BST.
function deleteNode(root, key) {
if (root == null) return null;
if (key < root.value) {
root.left = deleteNode(root.left, key);
} else if (key > root.value) {
root.right = deleteNode(root.right, key);
} else {
// Node found: handle 3 cases here
// 1. No child, 2. One child, 3. Two children
}
return root;
}
This code searches for the node with the given key and deletes it by adjusting pointers depending on the node's children.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive traversal down the tree to find the node.
- How many times: At most once per level of the tree, from root to leaf.
As the tree grows, the number of steps depends on the height of the tree.
| Input Size (n) | Approx. Operations (steps down tree) |
|---|---|
| 10 | About 3 to 4 steps |
| 100 | About 6 to 7 steps |
| 1000 | About 9 to 10 steps |
Pattern observation: The steps grow roughly with the height of the tree, which is about log of the number of nodes if the tree is balanced.
Time Complexity: O(h) where h is the tree height
This means the time to delete depends on how tall the tree is, not just how many nodes it has.
[X] Wrong: "Deletion always takes the same time regardless of tree shape."
[OK] Correct: If the tree is very unbalanced (like a linked list), deletion can take much longer because you must go through many nodes.
Understanding deletion time helps you explain how tree shape affects performance, a key skill in data structure questions.
"What if the BST is always perfectly balanced? How would that change the deletion time complexity?"