AVL树双重旋转错误
AVL Tree Double Rotation error
我正在为学校做一个项目,该项目涉及使用迭代插入函数实现AVL树,我遇到了一个问题。
我不能100%确定我没有做什么,但我的程序没有给出正确的输出。
以下是我的插入函数:
bool AVLTree::insert(string ss, string na){
AVLNode* newNode = new AVLNode(ss, na);
updateHeight(newNode);
//Tree is empty, make the new Node the root of a new tree
if(getRoot() == nullptr){
root = newNode;
print();
return true;
}
//Tree is not empty
else{
AVLNode* checkPoint;
checkPoint = root;
while(checkPoint != nullptr){
//If the ssn is already in the tree
if(checkPoint->ssn.compare(newNode->ssn) == 0){
return false;
}
else if(checkPoint->ssn.compare(newNode->ssn) > 0){
if(checkPoint->left == nullptr){
break;
}
checkPoint = checkPoint->left;
}
else{
if(checkPoint->right == nullptr){
break;
}
checkPoint = checkPoint->right;
}
}
if(newNode->ssn.compare(checkPoint->ssn) < 0){
checkPoint->left = newNode;
}
else{
checkPoint->right = newNode;
}
updateHeight(checkPoint);
balance(root);
print();
return true;
}
这是我到目前为止提出的功能,对于我的项目,我得到了平衡功能和updateHeight,我将在这里提供:
AVLNode* AVLTree::balance(AVLNode* node){
updateHeight(node);
if (balanceFactor(node) == 2) {
if (balanceFactor(node->left) < 0) {
node->left = rotateLeft(node->left); // for left right case
}
AVLNode* temp = rotateRight(node);
updateHeight(temp);
return temp;
}
if (balanceFactor(node) == -2) {
if (balanceFactor(node->right) > 0) {
node->right = rotateRight(node->right); // for right left case
}
AVLNode* temp2 = rotateLeft(node);
updateHeight(temp2);
return temp2;
}
return node;
更新高度:
void AVLTree::updateHeight(AVLNode* node){
int hl = height(node->left);
int hr = height(node->right);
node->height = (hl>hr ? hl : hr) + 1;
}
基本上,我的任务是实现插入和删除功能。我对avl树的输入顺序是:
5、8、9、3、6、7、5
我的输出是:
8
/
5 9
/
3 6
/
2 7
应该在什么时候:
6
/
3 8
/ /
2 5 7 9
回到我的插入函数,我认为问题是我没有在每次插入节点时正确地更新高度。该程序可以很好地处理单次旋转,但双次旋转不起作用。任何帮助都将不胜感激。
您必须检查并平衡节点插入点上方的所有树级别。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的旋转数组代码给出了大数组大小的错误
- D3DXMatrix旋转轴旋转错误的轴
- 四元数旋转错误
- 旋转数组 - 错误
- 直接相机旋转的错误控制
- AVL树双重旋转错误
- GLM::旋转似乎会导致错误的旋转
- 有人能在我的代码中找到矩阵旋转的错误
- 旋转实现错误
- boost::几何多边形的 outer() 在多边形旋转后有错误的坐标