0
0
Data Structures Theoryknowledge~5 mins

Deletion in BST in Data Structures Theory - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Deletion in BST
O(h)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the tree grows, the number of steps depends on the height of the tree.

Input Size (n)Approx. Operations (steps down tree)
10About 3 to 4 steps
100About 6 to 7 steps
1000About 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding deletion time helps you explain how tree shape affects performance, a key skill in data structure questions.

Self-Check

"What if the BST is always perfectly balanced? How would that change the deletion time complexity?"