Deleting a Node from a Binary Search Tree (BST)
When deleting a node from a Binary Search Tree (BST), three cases must be
considered, depending on the number of children the node has. The structure of the
BST must remain intact after deletion, maintaining its properties:
All nodes in the left subtree are less than the node.
All nodes in the right subtree are greater than the node.
Case 1: Node has no children (Leaf Node)
Description: This is the simplest case. The node to be deleted is a leaf node (has
no children).
Action: Simply remove the node from the tree.
Example:
BST before deletion:
markdown
Copy code
20
/ \
10 30
/ \
25 35
Delete 25:
markdown
Copy code
20
/ \
10 30
\
35
Case 2: Node has one child
Description: The node to be deleted has one child, either left or right.
Action: Replace the node with its only child.
Example:
BST before deletion:
markdown
Copy code
20
/ \
10 30
/
25
Delete 30:
markdown
Copy code
20
/ \
10 25
Case 3: Node has two children
Description: The node to be deleted has two children (both left and right subtrees).
Action: Replace the node with either:
Inorder Successor (smallest value in the right subtree).
Inorder Predecessor (largest value in the left subtree).
Steps for Deletion:
Find the inorder successor (or predecessor) of the node.
Replace the value of the node with that of the successor (or predecessor).
Recursively delete the successor (or predecessor) node.
Example:
BST before deletion:
markdown
Copy code
20
/ \
10 30
/ \
25 35
Delete 20 (node with two children):
Inorder successor is 25.
Replace 20 with 25.
Delete 25 from the right subtree.
BST after deletion:
markdown
Copy code
25
/ \
10 30
\
35
Summary:
Case 1: Simply remove the node (no children).
Case 2: Replace the node with its only child.
Case 3: Replace the node with its inorder successor (or predecessor), and remove the
successor (or predecessor) from the tree.