37. Insertion and Removing the Smallest for Binary Search Trees


Inserting into a binary search tree

To insert a value, just find where that value would have been, had it already been in the tree, then add the value as a new leaf. For example, inserting 13 as shown below would result in the following change.

The actual insertion takes place when a null tree is encountered. The null tree is replaced by a leaf. If the value to be inserted is already in the tree, nothing is done.

  //==========================================
  //                insert
  //==========================================
  // insert(x,T) inserts x (destructively) into
  // binary search tree T. If x is already a
  // member of T, it does nothing.
  //==========================================

  void insert(int x, Tree& T)
  {
    if(T == NULL)
    {
      T = new Node(x, NULL, NULL);
    }
    else if(x < T->item)
    {
      insert(x, T->left);
    }
    else if(x > T->item)
    {
      insert(x, T->right);
    }
  }

Notice that parameter T is passed by reference. The first case needs to change the pointer that is stored in T. Also notice that there is no case for x = T->item since insert is supposed to do nothing when x already occurs in the tree.


Removing the smallest value from binary search tree

Suppose that we want to remove the smallest value from a nonempty binary search tree. Finding the smallest value is easy. It is a matter of going to the left as far as possible. Then we remove the node that is found there, replacing it by its right subtree. Here is an example.

Here is an implementation of that idea.

  //====================================================
  //               removeSmallest
  //====================================================
  // removeSmallest(T) removes the smallest value from
  // binary search tree T and returns the value that
  // was removed.
  //
  // Requirement: T must not be an empty tree.
  //====================================================

  int removeSmallest(Tree& T)
  {
    if(T->left == NULL)
    {
      int  result = T->item;
      Tree p      = T;

      T = T->right;
      delete p;
      return result;
    }
    else 
    {
      return removeSmallest(T->left);
    }
  }

Exercises

  1. What tree do you get if you insert 25 into the following binary search tree?

    Answer

  2. What tree do you get if you insert 7 into the following binary search tree?

    Answer

  3. What tree do you get if you insert 11 into the following binary search tree?

    Answer