方法如下:
如果x没有子节点,或者只有一个孩子,直接将x切下
如果x有两个孩子,我们有其右子树中的最小值替换x,然后将左子树中的这一最小值切掉
/**
* 删除节点
* */
public BSTreeNode<T> Delete(BSTreeNode<T> t ,BSTreeNode<T> x) {
if (x == null) return Root;
BSTreeNode<T> root = t;
BSTreeNode<T> oldX= x;
BSTreeNode<T> parent = x.parent;
if (x.left == null) {
x = x.right;
} else if (x.right == null) {
x = x.left;
} else {
BSTreeNode<T> y = Min(x.right);
x.key = y.key;
if (y.parent != x) {
y.parent.left = y.right;
} else {
x.right = y.right;
}
return root;
}
if (x != null) {
x.parent = parent;
}
if (parent == null) {
root = x;
} else {
if (parent.left == oldX) {
parent.left = x;
} else {
parent.right = x;
}
}
return Root;
}