BIT201 ยท 2082 ยท 5 marks
List the limitation of recursion. How do you delete the node in BST? [2+3]
List the limitation of recursion. How do you delete the node in BST? [2+3]
Quick answer
When deleting a node from a Binary Search Tree, there are three cases: Simply remove the node by setting the parent's pointer to NULL; Replace the node with its only child (bypass the node); Find the inorder successor (smallest node in the right subtree) OR inorder predecessor (largest node in the left subtree).
Limitations of Recursion and Deletion in BST
Limitations of Recursion [2 marks]
-
Stack Overflow: Each recursive call uses stack memory. For deep recursion (large input), the call stack may overflow, causing program crash.
-
High Memory Usage: Every function call requires stack frame allocation (for parameters, local variables, return address), consuming more memory than iterative solutions.
-
Slower Execution: Function call overhead (pushing/popping stack frames) makes recursion slower compared to equivalent iterative approaches.
-
Difficult to Trace/Debug: The flow of recursive programs is harder to follow and debug compared to iterative programs.
-
Redundant Computations: Without memoization, some recursive algorithms (e.g., naive Fibonacci) recompute the same subproblems repeatedly.
Deletion of a Node in BST [3 marks]
When deleting a node from a Binary Search Tree, there are three cases:
Case 1: Node is a Leaf Node (No Children)
- Simply remove the node by setting the parent's pointer to
NULL.
Delete 20:
30 30
/ --> /
20 (NULL)
Case 2: Node has One Child
- Replace the node with its only child (bypass the node).
Delete 30:
30 20
/ -->
20
Case 3: Node has Two Children
- Find the inorder successor (smallest node in the right subtree) OR inorder predecessor (largest node in the left subtree).
- Copy its value to the node to be deleted.
- Delete the inorder successor/predecessor (which has at most one child).
Delete 50:
50 60
/ \ --> / \
30 70 30 70
/
60
Inorder successor of 50 is 60.
Copy 60 to node 50, then delete original 60.
Algorithm (Pseudocode)
DELETE(root, key):
if root == NULL:
return NULL
if key < root.data:
root.left = DELETE(root.left, key)
else if key > root.data:
root.right = DELETE(root.right, key)
else:
// Case 1 & 2: 0 or 1 child
if root.left == NULL:
return root.right
else if root.right == NULL:
return root.left
// Case 3: 2 children
successor = FIND_MIN(root.right)
root.data = successor.data
root.right = DELETE(root.right, successor.data)
return root
Summary Table
| Case | Condition | Action |
|---|---|---|
| 1 | No children | Remove node directly |
| 2 | One child | Replace node with its child |
| 3 | Two children | Replace with inorder successor, then delete successor |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.