First, you need to find the node you want to delete, and search first.
There are three situations for the node to be deleted.
- Leaf node: directly delete and set the pointer of its parent node to NULL
- A node with only one child node: Point the pointer of its parent node to its child node
- A node with two child nodes: replace it with the smallest element of the right subtree or the largest element of the left subtree
//定义二叉树
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;
}