Exemple #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
    }