我编写了这段代码,用于删除没有兄弟节点且父节点也没有兄弟节点的节点:
void DeleteSingles(struct BinaryTreeNode* root)
{
struct BinaryTreeNode* parent,*child;
if(!root) return;
DeleteSingles(root->left);
if((root->left==NULL)^(root->right==NULL))//checking from the root if it has a single child
{
parent=(root->left)?root->left:root->right;//let the parent be that node that has no siblings
if((parent->left==NULL)^(parent->right==NULL))//checking if that parent has a child with no sibilings
{
child=(parent->left)?parent->left:parent->right;//save the target node for deletion
if(child->left==NULL && child->right==NULL)//when the node to be deleted has no children
{
parent->left=parent->right=NULL;
}
else if((child->left!=NULL)&&(child->right!=NULL))//when the node to be deleted has 2 children
{
parent->left=child->left;
parent->right=child->right;
}
free(child);
}
}
DeleteSingles(root->right);
}
例如,当我向我的BST插入5,4,3,2,1,6时,该功能应该删除1和2,因为他们都没有兄弟姐妹,而且他们的父母都没有兄弟姐妹,我我不确定6是否满足这个条件。
但是,当要删除的节点没有子节点时,此代码似乎只能工作,当我插入值5,4,3,2,1,-3,-2,6时,它应该删除1,2。< / p>
我的条件是不正确还是我错过了什么?
然后我在评论的建议后尝试了以下内容:
void DeleteSingles(struct BinaryTreeNode** root)
{
struct BinaryTreeNode* parent,*child;
if(!(*root)) return;
DeleteSingles(&((*root)->left));
DeleteSingles(&((*root)->right));
if((*root)->left==NULL ^ (*root)->right==NULL)
{
parent=((*root)->left == NULL)?(*root)->right:(*root)->left;
if(parent->left==NULL ^ parent->right==NULL)
{
child=(parent->left==NULL)?parent->right:parent->left;
if(child->left==NULL && child->right==NULL)
{
parent->left=parent->right=NULL;
}
else if(child->left!=NULL && child->right==NULL)
{
parent->left=child->left;
parent->right=child->right;
}
printf("\nAbout to delete %d\n",child->data);
free(child);
}
}
}
但是当我的BST为5,4,3,2,1,-3,-2,6时,当-2和-3不满足条件时,它会删除-2,-3,1,2。 / p>