【C++】AVL树(旋转、平衡因子)
#include <iostream>
using namespace std;
struct AVLNode {
int key;
int height;
AVLNode *left;
AVLNode *right;
AVLNode(int k) : key(k), height(0), left(nullptr), right(nullptr) {}
};
int getHeight(AVLNode *node) {
return node ? node->height : 0;
}
// 更新节点的高度
void updateHeight(AVLNode *node) {
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
}
// 获取节点的平衡因子
int getBalanceFactor(AVLNode *node) {
return getHeight(node->left) - getHeight(node->right);
}
// 对以node为根的AVL树进行左旋转
AVLNode* leftRotate(AVLNode *node) {
AVLNode *rightNode = node->right;
node->right = rightNode->left;
rightNode->left = node;
updateHeight(node);
updateHeight(rightNode);
return rightNode;
}
// 对以node为根的AVL树进行右旋转
AVLNode* rightRotate(AVLNode *node) {
AVLNode *leftNode = node->left;
node->left = leftNode->right;
leftNode->right = node;
updateHeight(node);
updateHeight(leftNode);
return leftNode;
}
// 对以node为根的AVL树进行插入后的调整
AVLNode* insert(AVLNode *node, int key) {
if (node == nullptr) {
return new AVLNode(key);
}
if (key < node->key) {
node->left = insert(node->left, key);
// 如果左子树高,需要进行右旋转
if (getBalanceFactor(node) == -2) {
if (key < node->left->key) {
node = rightRotate(node);
} else {
node->left = leftRotate(node->left);
node = rightRotate(node);
}
}
} else {
node->right = insert(node->right, key);
// 如果右子树高,需要进行左旋转
if (getBalanceFactor(node) == 2) {
if (key > node->right->key) {
node = leftRotate(node);
} else {
node->right = rightRotate(node->right);
node = leftRotate(node);
}
}
}
updateHeight(node);
return node;
}
int main() {
AVLNode *root = nullptr;
int keys[] = {1, 2, 3, 4, 5, 6, 7};
for (int key : keys) {
root = insert(root, key);
}
// 中序遍历AVL树以验证其平衡
function<void(AVLNode*)> inorder = [&](AVLNode *node)
if (node != nullptr) {
inorder(node->left);
cout << node->key << " ";
inorder(node->right);
}
};
inorder(root);
return 0;
}
这段代码实现了AVL树的插入操作,包括旋转和平衡因子的计算。它首先定义
评论已关闭