首先需要找到要删除的结点,先进行查找
需要删除的结点有三种情况
- 叶结点:直接删除,并将其父结点的指针置为NULL
- 只有一个子结点的结点:将其父结点的指针指向其的子结点
- 有两个子结点的结点:用右子树的最小元素或左子树的最大元素代替其
//定义二叉树
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;
}