C++平衡二叉树,要求使用类模板,只包含插入删除功能,不要查询功能,代码实现
时间: 2024-09-15 22:14:15 浏览: 52
```cpp
#include <iostream>
template <typename T>
class AVLTree {
public:
struct Node {
T data;
Node* left;
Node* right;
int height;
Node(T value) : data(value), left(nullptr), right(nullptr), height(1) {}
};
AVLTree() : root(nullptr) {}
void insert(T value) {
root = insert(root, value);
}
void remove(T value) {
root = remove(root, value);
}
private:
Node* root;
int getHeight(Node* node) {
if (node == nullptr) {
return 0;
}
return node->height;
}
int getBalanceFactor(Node* node) {
if (node == nullptr) {
return 0;
}
return getHeight(node->left) - getHeight(node->right);
}
Node* rotateRight(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
y->height = std::max(getHeight(y->left), getHeight(y->right)) + 1;
x->height = std::max(getHeight(x->left), getHeight(x->right)) + 1;
return x;
}
Node* rotateLeft(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = std::max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = std::max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
Node* insert(Node* node, T value) {
if (node == nullptr) {
return new Node(value);
}
if (value < node->data) {
node->left = insert(node->left, value);
} else if (value > node->data) {
node->right = insert(node->right, value);
} else {
return node;
}
node->height = 1 + std::max(getHeight(node->left), getHeight(node->right));
int balance = getBalanceFactor(node);
if (balance > 1 && value < node->left->data) {
return rotateRight(node);
}
if (balance < -1 && value > node->right->data) {
return rotateLeft(node);
}
if (balance > 1 && value > node->left->data) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}
if (balance < -1 && value < node->right->data) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}
return node;
}
Node* minValueNode(Node* node) {
Node* current = node;
while (current->left != nullptr) {
current = current->left;
}
return current;
}
Node* remove(Node* root, T value) {
if (root == nullptr) {
return root;
}
if (value < root->data) {
root->left = remove(root->left, value);
} else if (value > root->data) {
root->right = remove(root->right, value);
} else {
if (root->left == nullptr || root->right == nullptr) {
Node* temp = root->left ? root->left : root->right;
if (temp == nullptr) {
temp = root;
root = nullptr;
} else {
*root = *temp;
}
delete temp;
} else {
Node* temp = minValue
阅读全文