Removal
Last updated
Last updated
In order to delete a node, we must be sure to link up the subtree(s) of the node properly. Let us consider the following situations.
Suppose we start with the following binary search tree:
Suppose we were to remove 7 from the tree. Removing this node is relatively simple, we simply have to ensure that the pointer that points to it from node 6 is set to NULL and delete the node:
Now, Lets remove the node 6 which has only a left child but no right child. This is also easy. all we need to do is make the pointer from the parent node point to the left child.
Thus our tree is now:
Now suppose we wanted to remove a node like 8. We cannot simply make 4 point to 8's child as there are 2 children. While it is possible to do something like make parent point to right child then attach left child to the left most subtree of the right right child, doing so would cause the tree to be bigger and is not a good solution.
Instead, we should find the inorder successor (next biggest descendent) to 8 and promote it so that it replaces 8.
The inorder successor can be found by going to the right child of 8 then going as far left as possible. In this case, 9 is the inorder sucessor to 8:
The inorder successor will either be a leaf node or it will have a right child only. It will never have a left child because we found it by going as far left as possible.
Once found, we can promote the inorder successor to take over the place of the node we are removing. The parent of inorder successor must link to the right child of the inorder succesor.
In the end we have: