Primero, debe encontrar el nodo que desea eliminar y buscar primero
Hay tres situaciones para el nodo que desea eliminar.
- Nodo hoja: elimine directamente y establezca el puntero de su nodo principal en NULL
- Un nodo con un solo nodo hijo: apunte el puntero de su nodo padre a su nodo hijo
- Un nodo con dos nodos secundarios: reemplácelo con el elemento más pequeño del subárbol derecho o el elemento más grande del subárbol izquierdo
//定义二叉树
typedef struct TreeNode *BinTree;
typedef BinTree Position;
typedef int ElementType;
struct TreeNode
{
ElementType data;
BinTree left;
BinTree right;
};
//查找最小值
BinTree FindMin(BinTree bst)
{
if(bst)
while(bst->left)
bst=bst->left;
return bst;
}
BinTree Delete(ElementType x,BinTree bst)
{
BinTree tmp;
if(!bst)
cout<<"无该元素";
else if(x<bst->data)
bst->left=Delete(x,bst->left);
else if(x>bst->data)
bst->right=Delete(x,bst->right);
else //找到了
{
if(bst->left&&bst->right) //有左右两个子结点
{
tmp=FindMin(bst->right); //在右子树找到最小值
bst->data=tmp->data; //用最小值替换该值
bst->right=Delete(bst->data,bst->right);//删除右子树的最小值
}
else //无子结点或只有一个
{
tmp=bst;
if(!bst->left) //无左结点
bst=bst->right;
else if(!bst->right) //无右结点
bst=bst->left;
free(tmp);
}
}
return bst;
}