Ejemplo n.º 1
0
    @Override
    protected BSTVertex delete(BSTVertex T, Name v) {
      if (T == null) return T; // cannot find the item to be deleted

      if (T.key.babyName.equals(v.babyName)) { // this is the node to be deleted
        if (T.left == null && T.right == null) { // this is a leaf
          T = null; // simply erase this node
        } else if (T.left == null && T.right != null) { // only one child at right
          T.right.parent = T.parent;
          T = T.right; // bypass T
        } else if (T.left != null && T.right == null) { // only one child at left
          T.left.parent = T.parent;
          T = T.left; // bypass T
        } else { // has two children, find successor
          Name successorV = successor(v);
          T.key = successorV; // replace this key with the successor's key
          T.right = delete(T.right, successorV); // delete the old successorV
        }
      } else if (T.key.babyName.compareTo(v.babyName) < 0) { // search to the right
        T.right = delete(T.right, v);
      } else { // search to the left
        T.left = delete(T.left, v);
      }
      updateHeight(T);
      updateSize(T);
      // Balance the tree after deletion
      T = balance(T);
      return T; // return the updated BST
    }
Ejemplo n.º 2
0
  protected BSTVertex delete(BSTVertex T, int v) {
    if (T == null) return T; // cannot find the item to be deleted

    if (T.key == v) { // this is the node to be deleted
      if (T.left == null && T.right == null) // this is a leaf
      T = null; // simply erase this node
      else if (T.left == null && T.right != null) { // only one child at right
        BSTVertex temp = T;
        T.right.parent = T.parent;
        T = T.right; // bypass T
        temp = null;
      } else if (T.left != null && T.right == null) { // only one child at left
        BSTVertex temp = T;
        T.left.parent = T.parent;
        T = T.left; // bypass T
        temp = null;
      } else { // has two children, find successor
        int successorV = successor(v);
        T.key = successorV; // replace this key with the successor's key
        T.right = delete(T.right, successorV); // delete the old successorV
      }
    } else if (T.key < v) // search to the right
    T.right = delete(T.right, v);
    else // search to the left
    T.left = delete(T.left, v);
    return T; // return the updated BST
  }