previous | start | next

Delete Method (so far):

We haven't handled the bad case 2 yet, but let's see what the code would be just to handle the search AND case 1.

Begin with the usual public/private pair of methods, remembering that deletion modifies the tree (like put, but unlike size()). In particular the root might change.

public void delete(int k)
{
  root = delete(root, k);
}

public Node delete(Node t, int k)
{
  if (t == null) {
     return null;  // k not in the tree
  }
  // Find the node to delete: the one containing k
  if (k < t.key) {
     t.left = delete(t.left, k);
  } else if (k > t.key) {
    t.right = delete(t.right, k);
  } else { // we found it. Now delete t
    if (t.left == null) { // So we are in case 1
       return t.right;
    } else if (t.right == null) { // Also in case 1
       return t.left;
    } else {
      // THE BAD CASE 2 - t has two children
    }
  }
  return t;
}


previous | start | next