- 2075 Baisakh · 5 marks
Delete BST node with one child
Short answer
To delete a node with one child, bypass the node by linking its parent to the child. For example, deleting 18 with left child 13: parent 10 now points to 13. This preserves BST order.
Explain deletion of node with one child in BST with suitable example.
Rule: if the node to be deleted has exactly one child, the node is removed and its only child (with the whole subtree below it) takes its place by linking the child directly to the deleted node's parent. The BST property is preserved because the child subtree already lies in the correct range for that position.
Steps
- Search for the node X (and keep a pointer to its parent P).
- Let C be the only child of X (left or right).
- If X is the root, make C the new root.
- Else if X is the left child of P, set
P->left = C; otherwise setP->right = C. - Free X.
Example
Delete 18 from the BST (18 has only a left child 13):
Before: After:
20 20
/ \ / \
10 47 10 47
/ \ / \
4 18 <- delete 4 13
/
13
Parent 10 now points to 13 instead of 18. In-order traversal before: 4 10 13 18 20 47; after: 4 10 13 20 47, still sorted.
Code
struct node { int info; struct node *left, *right; };
struct node *delete_one_child(struct node *root, int key) {
struct node *p = NULL, *x = root, *c;
while (x != NULL && x->info != key) { /* find x and its parent */
p = x;
x = (key < x->info) ? x->left : x->right;
}
if (x == NULL) return root; /* key not found */
c = (x->left != NULL) ? x->left : x->right; /* the only child */
if (p == NULL) root = c; /* deleting the root */
else if (p->left == x) p->left = c;
else p->right = c;
free(x);
return root;
}
Time: O(h), where h is the height of the tree.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Insert and delete kth node in doubly linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Delete last node of doubly linked list · Data Structure and Algorithm, chapter 4
- Insert and delete before a node, singly linked · Data Structure and Algorithm, chapter 4
- Delete Kth node from doubly linked list · Data Structure and Algorithm, chapter 4
- AVL delete then insert gives same tree? · Data Structure and Algorithm, chapter 6
- Boundary derivative with one-sided differences · Applied Computational Fluid Dynamics, chapter 3
- Linear shape functions for one-dimensional element · Finite Element Method, chapter 5
- Variational approach for one-dimensional heat conduction · Finite Element Method, chapter 5