39A. Deletion from a Binary Search Tree

It is easy to remove a value from an empty tree; we simply say that removing x from a tree that does not contain x has no effect. It is also easy to remove x from a tree T where x does not occur in the root. Just do a recursive call to remove x from either the left subtree of T or the right subtree of T, whichever is appropriate.

All that is left is removing x from a tree in the case where x occurs in the root. Suppose that one of the subtrees of T is empty. Then removing x is easy: replace T by its only nonempty subtree.

The same idea works even if both subtrees are empty. After finding that the left subtree is empty, replace T by its right subtree, whether that is empty or not.

There is only one remaining case: the value to remove is in the root of T and both subtrees of T are nonempty. To handle that case, start by removing the smallest value s from T 's right subtree. Then replace the value in the root of T by s.

Here is a definition of remove using those ideas.

  //====================================================
  //                remove
  //====================================================
  // remove(x,T) removes x from binary search tree T.
  // If x is not in T, it does nothing.
  //====================================================

  void remove(const int x, Tree& T)
  {
    if(T != NULL)
    {
      if(x < T->item)
      {
        remove(x, T->left);
      }
      else if(x > T->item)
      {
        remove(x, T->right);
      }
      else if(T->left == NULL)
      {
        Tree p = T;
        T = T->right;
        delete p;
      }
      else if(T->right == NULL)
      {
        Tree p = T;
        T = T->left;
        delete p;
      }
      else {
        T->item = removeSmallest(T->right);
      }
    }
  }

Exercises

  1. What tree do you get if your remove 5 from the following binary search tree, using the algorithm described above?

    Answer

  2. What tree do you get if you remove 15 from the following binary search tree, using the algorithm described above?

    Answer

  3. What tree do you get if you remove 10 from the following binary search tree, using the algorithm described above?

    Answer