我在C中实现AVL树,还需要创建一个迭代器。因此,我需要维护父节点以恒定时间遍历树。我在树木平衡期间难以维护父母。这就是我所拥有的:
/*Balance factor of -2 with Right Child -1*/
static AVLPtr RRRotation(AVLPtr root){
AVLPtr rightChild = root->rightChild;
root->rightChild = rightChild->leftChild;
if(rightChild->leftChild != NULL){
rightChild->leftChild->parent = root;
}
rightChild->leftChild = root;
if(rightChild != NULL){
rightChild->parent = root->parent;
}
if(root != NULL){
root->parent = rightChild;
}
return rightChild;
}
/*Balance factor of +2 with Left Child +1*/
static AVLPtr LLRotation(AVLPtr root){
AVLPtr leftChild = root->leftChild;
root->leftChild = leftChild->rightChild;
if(leftChild->rightChild != NULL){
leftChild->rightChild->parent = root;
}
leftChild->rightChild = root;
if(leftChild != NULL){
leftChild->parent = root->parent;
}
if(root != NULL){
root->parent = leftChild;
}
return leftChild;
}
/*Balance factor of -2 with Right Child +1*/
static AVLPtr RLRotation(AVLPtr root){
AVLPtr rightChild = root->rightChild;
AVLPtr temp = LLRotation(rightChild);
if(temp != NULL){
temp->parent = root;
}
root->rightChild = temp;
AVLPtr temp2 = RRRotation(root);
if(temp2 != NULL){
temp2->parent = root->parent;
}
return temp2;
}
/*Balance factor of +2 with Left Child -1*/
static AVLPtr LRRotation(AVLPtr root){
AVLPtr leftChild = root->leftChild;
AVLPtr temp = RRRotation(leftChild);
if(temp != NULL){
temp->parent = root;
}
root->leftChild =temp;
AVLPtr temp2 = LLRotation(root);
if(temp2 != NULL){
temp2->parent = root->parent;
}
return temp2;
}
我认为我在RL和LR轮换中做错了什么但似乎无法弄清楚是什么。此外,一些if语句可能不需要,但不应该重要。
答案 0 :(得分:0)
我检查了RRRotation
并没有看到任何错误,但发现很难遵循。快速检查LLRotation
也没有发现任何错误。我没有检查另外两个,因为到那时我的头在旋转。
在我看来,您可以使用更多局部变量来简化逻辑,这样可以更容易地验证逻辑。这是我写RRRotation
函数的方法。
static AVLPtr RRRotation(AVLPtr root)
{
AVLPtr parent = root->parent; // the parent of the root node
AVLPtr child = root->rightChild; // the child of the root node
AVLPtr baby = child->leftChild; // the child of the child node
child->parent = parent;
child->leftChild = root;
root->parent = child;
root->rightChild = baby;
if ( baby )
baby->parent = root;
}