在我的BST课程中,我使用以下函数来交换两个节点
void swapNodes(BSTNode *node1, BSTNode *node2)
{
if(node1->parent->left==node1)
node1->parent->left = node2;
else
node1->parent->right = node2;
if(node2->parent->left==node2)
node2->parent->left = node1;
else
node2->parent->right = node1;
BSTNode *temp;
temp->parent = node1->parent;
temp->left = node1->left;
temp->right = node1->right;
node1->parent = node2->parent;
node1->left = node2->left;
node1->right = node2->right;
node2->parent = temp->parent;
node2->left = temp->left;
node2->right = temp->right;
}
它需要两个节点指针并将它们交换。但是,当我调用此函数时,它会出现内存违规错误。我在这做错了什么?如果您知道在二叉树中交换两个节点的任何其他简单方法,请分享。
答案 0 :(得分:2)
这个问题比看起来更复杂,因为涉及树的根的特殊情况,当一个是另一个父项时交换两个项,并修复左右子项的父指针。这是一些有效的代码。我怀疑它可以在某种程度上变得更整洁更短。
void Swap(T* aP,T* aQ)
{
T* new_p_parent = aQ->iParent;
T* new_p_left = aQ->iLeft;
T* new_p_right = aQ->iRight;
T** new_p_link = &iRoot;
if (aQ->iParent)
new_p_link = aQ->iParent->iLeft == aQ ? &aQ->iParent->iLeft : &aQ->iParent->iRight;
T* new_q_parent = aP->iParent;
T* new_q_left = aP->iLeft;
T* new_q_right = aP->iRight;
T** new_q_link = &iRoot;
if (aP->iParent)
new_q_link = aP->iParent->iLeft == aP ? &aP->iParent->iLeft : &aP->iParent->iRight;
if (aQ->iParent == aP)
{
new_p_parent = aQ;
new_p_link = nullptr;
if (aP->iLeft == aQ)
new_q_left = aP;
else
new_q_right = aP;
}
else if (aP->iParent == aQ)
{
new_q_parent = aP;
new_q_link = nullptr;
if (aQ->iLeft == aP)
new_p_left = aQ;
else
new_p_right = aQ;
}
aP->iParent = new_p_parent;
aP->iLeft = new_p_left;
if (aP->iLeft)
aP->iLeft->iParent = aP;
aP->iRight = new_p_right;
if (aP->iRight)
aP->iRight->iParent = aP;
if (new_p_link)
*new_p_link = aP;
aQ->iParent = new_q_parent;
aQ->iLeft = new_q_left;
if (aQ->iLeft)
aQ->iLeft->iParent = aQ;
aQ->iRight = new_q_right;
if (aQ->iRight)
aQ->iRight->iParent = aQ;
if (new_q_link)
*new_q_link = aQ;
}
答案 1 :(得分:1)
BSTNode *temp;
未初始化