Binary Search Tree Erase Idea video (14 minutes) (Spring 2021)
In a BST, a node can have either 0, 1, or 2 child nodes. If the parent node were to be deleted, in each of these cases:
0 children: This is easy, nothing happens. The deleted node is a leaf, and can simply be removed from the tree.
1 child: This is also easy. The deleted node would be replaced with the child node, similarly to deleting a node from a singly linked list. One pointer update happens. (And dynamically allocated memory is handled with a delete!)
2 children: This is trickier. We have two options to replace the deleted node.
Option A: replace the deleted node with the biggest element from the left subtree
Option B: replace the deleted node with the smallest element from the right subtree
For example, in this tree, if the root node 5 were deleted, it could either be replaced with 4 (option A), or 7 (option B) If 2 were deleted, it could be replaced with either 1 (option A) or 3 (option B)
5
/ \
2 8
/ \ /
1 4 7
/
3
We will use Option A for now. We will replace a deleted node with the biggest element from the node's left subtree.
Thanks for Brian Foster for writing up these notes based on the video lectures.