我正在为我正在创建的文字游戏中使用的AVL树数据结构编写代码。 AVL树用于按字母顺序存储字典文本文件中的单词,以便快速方便地访问。我已经确认我可以将我的字典实现为二叉搜索树,但是我很难将其作为AVL树实现,更具体地说,当我在旋转后重新平衡时。
我通过简单地使用pre,in和postorder遍历来测试我的代码,看看我的整个树是否正确实现。我遇到的问题是我只能恢复6/22个单词。我已经找到了一个原因,即在围绕它执行旋转后我没有更新我的根,但由于某种原因它只在第一次旋转后更新根,并且从不在之后。
以下是代码:
我没有包含的唯一代码是getMax和getDiff。获取max返回两个子节点的最大高度,得到差值返回当前节点的余额。
此外,adjustHeightsH是一个帮助函数,用于更新最近插入的节点上方每个节点的高度。
void AVLTree::adjustHeights(NodeT *n){
adjustHeightsH(n);
if(AVLflag){
if(n->parent == NULL){
return;
}
NodeT *temp = n->parent;
int balance = getDiff(temp);
while(temp != NULL){
balance = getDiff(temp);
if(balance > 1 && getDiff(temp->left) >= 0){
rotateRight(temp);
cout << "rotated right" << endl;
}
else if(balance < -1 && getDiff(temp->right) <= 0){
rotateLeft(temp);
cout << "rotated left" << endl;
}
else if(balance > 1 && getDiff(temp->left) < 0){
temp->left = rotateLeft(temp->left);
rotateRight(temp);
cout << "rotated left right" << endl;
}
else if(balance < -1 && getDiff(temp->right) > 0){
temp->right = rotateRight(temp->right);
rotateLeft(temp);
cout << "rotated right left" << endl;
}
temp = temp->parent;
}
}
}
void AVLTree::adjustHeightsH(NodeT *n){
NodeT *temp = n;
while(temp != NULL){
temp->height = getMax(temp) + 1;
temp = temp->parent;
}
}
NodeT *AVLTree::rotateRight(NodeT *n){
NodeT *temp = n->left;
NodeT *temp2 = temp->right;
if(n == root){
temp->right = n;
n->left = temp2;
temp->parent = NULL;
n->parent = temp;
root = temp;
cout << "NEW ROOT" << endl;
}
else{
temp->right = n;
n->left = temp2;
temp->parent = n->parent;
n->parent = temp;
}
n->height = getMax(n) + 1;
temp->height = getMax(temp)+1;
return temp;
}
NodeT *AVLTree::rotateLeft(NodeT *n){
NodeT *temp = n->right;
NodeT *temp2 = temp->left;
if(n == root){
temp->left = n;
n->right = temp2;
temp->parent = NULL;
n->parent = temp;
root = temp;
cout << "NEW ROOT" << endl;
}
else{
temp->left = n;
n->right = temp2;
temp->parent = n->parent;
n->parent = temp;
}
n->height = getMax(n) + 1;
temp->height = getMax(temp) + 1;
return temp;
}