Deletion from a BST
When inserting a key, we were allowed to choose where in the tree it should go. The deletion operation doesn't appear to allow us that flexibility; deletion of some keys will be easy (leaves or keys with only one child), but our deletion method has to be able to delete any key from the tree.
Here are a bunch of binary search trees that might result from deleting the root of the following tree:
BST
Think about which ones are reasonable and answer this poll.
tree 1 tree 2 tree 3 tree 4 tree 5 tree 6
Tree Tree Tree Tree Tree Tree
tree 7 tree 8 tree 9 tree 10 tree 11 tree 12
Tree Tree Tree Tree Tree Tree
A good way to delete a key
The following algorithm for deletion has the advantage of minimizing restructuring and unbalancing of the tree. The method returns the tree that results from the removal.
  1. Find the node to be removed. We'll call it remNode. If it's a leaf, remove it immediately by returning null. If it has only one child, remove it by returning the other child node.
  2. Otherwise, remove the inorder successor of remNode, copy its myItem into remNode, and return remNode.
Q: What is a inorder successor?
A: It is just the node that would appear after the remNode if you were to do an inorder traversal of the tree.
An example is diagrammed below. The node to remove is the node containing 4. It has two children, so it's not an easy node to remove. We locate the node with 4's inorder successor, namely 5. The node containing 5 has no children, so it's easy to delete. We copy the 5 into the node that formerly contained 4, and delete the node that originally contained 5.
before deletion after deletion
BST - Before Deletion BST - After Deletion
Discussion: A general property of the inorder successor
Where in a BST is the inorder successor of a node whose right child is null?
Note: The node in question is not necessarily the root node.
Contribute at least one post to this discussion on Piazza. Do not duplicate posts your classmates have made. Follow the link to your appropriate lab section.
Self-Test: Inorder successor
Suppose myNode is the root node in a BST with both a left child and a right child. Will sucNode, the inorder successor of myNode, always have a null left child?
  1. Yes, always
  2. No, only sometimes
  3. No, never
Toggle Solution
Yes, always
Animations of BST algorithms
Experiment with this visualization of a binary search tree, which displays the result of insertions and deletions in a binary search tree. Try inserting a key that ends up as a right child and another key that ends up as a left child. Add some more nodes to the tree, then delete some of them: a node with no children, a node with one child, and a node with two children.