38A. Deletion from a Binary Search Tree

If x occurs at the root of T and one of the subtrees of the root is empty, then removing x is easy. Just replace the tree by the one that is not empty.

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. Also, a similar idea works even when the value to be removed is not at the root, as long as at least one of its subtrees is empty. For example, here is how to remove a value from a subtree, where the left subtree of that subtree is empty.

Removing a value where both subtrees are nonempty is more involved. First, we remove the smallest value s from the right subtree, then replace the value that is supposed to removed by s.

Here are definitions of remove and removeSmallest.

  //====================================================
  //                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