So when I delete in binary search tree, do I need to have like 7 different cases i.e.
- Left Leaf;
- Right Leaf;
- Left child with only left child. //i.e the node to be deleted is the left child of it s parent and it has only left child.
- Left Child with only right child.
- Right child with only left child.
- Right child with only right child.
- Node to be deleted has both the children i.e. right and left.
Now when this code is using if-else
it gets pretty nasty.. is there any other way of doing this.
这里,我的准则
if(current->left==NULL && current->right==NULL && current->key<prev->key) //left leaf
prev->left=NULL;
else if(current->left==NULL && current->right==NULL && current->key>prev->key) // right leaf
prev->right=NULL;
else if(current->left!=NULL && current->right==NULL && current->key<prev->key) // left child with one child
prev->left=current->left;
else if(current->left==NULL && current->right!=NULL && current->key<prev->key)
prev->left=current->right;
else if(current->left!=NULL && current->right==NULL && current->key>prev->key)
prev->right=current->left;
else if(current->left==NULL && current->right!=NULL && current->key>prev->key)
prev->right=current->left;
else if(current->left!=NULL && current->right!=NULL)
{
check=current->right;
check1=check;
while(check->left!=NULL)
{
check1=check;
check=check->left;
}
*current=*check;
check1->left=NULL;
}