previous | start | next

Completed code for delete

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
      Node s = min(t.right);
      t.key = s.key;
      t.right = delete(t.right, t.key);
    }
  }
  return t;
}


previous | start | next