当节点有2个子节点时,我正在尝试从BST中删除该节点,但遇到了我无法理解的问题。
void deleteNode(NODE ** ROOT, int data)
{
printf("Root: %d\nData: %d\n", (*ROOT)->data, data);
NODE * nodeToDelete = searchTree(ROOT, data);
if(nodeToDelete == NULL)
{
printf("Node was not found and could not delete from tree.\n");
return;
}
else {
// There are three cases for deleting a Node.
// 1. Node we're deleting has no Children.
// 2. Node we're deleting has 1 child.
// 3. Node we're deleting has 2 children.
if(data == (*ROOT)->data)
{
if((*ROOT)->leftChild == NULL && (*ROOT)->rightChild == NULL)
{
printf("Deleting %d\n", (*ROOT)->data);
free(*ROOT);
return;
}
else if((*ROOT)->leftChild != NULL && (*ROOT)->rightChild == NULL)
{
NODE * temp = (*ROOT)->leftChild;
(*ROOT) = temp;
free((*ROOT)->leftChild);
return;
}
else if((*ROOT)->rightChild != NULL && (*ROOT)->leftChild == NULL)
{
NODE * temp = (*ROOT)->rightChild; // Create a pointer to the current Root's Right Child.
(*ROOT) = temp; // Set the current root to it's right child.
free((*ROOT)->rightChild); // Free the right child from memory.
return;
}
else { // Case #3: Two Children.
NODE * min = findMinimumNode(&(*ROOT)->rightChild);
printf("Min: %d\n", min->data);
int minValue = min->data;
(*ROOT)->data = minValue;
deleteNode(&(*ROOT)->rightChild, minValue);
}
}
else if(data < (*ROOT)->data)
{
if((*ROOT)->leftChild != NULL)
deleteNode(&(*ROOT)->leftChild, data);
else
return;
}
else if(data > (*ROOT)->data)
{
if((*ROOT)->rightChild != NULL)
deleteNode(&(*ROOT)->rightChild, data);
else
return;
}
}
}
在前两个情况下,当没有孩子并且只有一个孩子时,情况会非常好。我还有一个findMinimumNode方法,该方法返回子树的最小节点。我当前的树是:3 10 15 17 27 35 37 45 67 71 82
当我尝试删除45时,应将45替换为67,因为45有两个子代,而45的最小值的右子树是67。我试图将67替换为45,然后遍历新的67,即71,并删除旧的67,即71的左侧。
但是它一直在打印:3 10 15 17 27 35 37 67