C++平衡二叉树,要求使用类模板,包括插入删除功能,代码实现
时间: 2024-09-15 20:14:19 浏览: 76
平衡二叉树是一种自平衡的二叉搜索树,它可以在插入和删除操作后保持树的高度尽可能小。常见的平衡二叉树有AVL树和红黑树。这里我们以AVL树为例,实现一个简单的C++平衡二叉树类模板。
```cpp
#include <iostream>
#include <algorithm>
template <typename T>
class AVLTree {
public:
struct Node {
T key;
int height;
Node* left;
Node* right;
Node(T k) : key(k), height(1), left(nullptr), right(nullptr) {}
};
AVLTree() : root(nullptr) {}
~AVLTree() {
clear(root);
}
void insert(T key) {
root = insert(root, key);
}
void remove(T key) {
root = remove(root, key);
}
private:
Node* root;
int height(Node* node) {
return node ? node->height : 0;
}
int balanceFactor(Node* node) {
return height(node->left) - height(node->right);
}
void updateHeight(Node* node) {
node->height = std::max(height(node->left), height(node->right)) + 1;
}
Node* rotateRight(Node* y) {
Node* x = y->left;
y->left = x->right;
x->right = y;
updateHeight(y);
updateHeight(x);
return x;
}
Node* rotateLeft(Node* x) {
Node* y = x->right;
x->right = y->left;
y->left = x;
updateHeight(x);
updateHeight(y);
return y;
}
Node* balance(Node* node) {
updateHeight(node);
if (balanceFactor(node) == 2) {
if (balanceFactor(node->left) < 0) {
node->left = rotateLeft(node->left);
}
return rotateRight(node);
} else if (balanceFactor(node) == -2) {
if (balanceFactor(node->right) > 0) {
node->right = rotateRight(node->right);
}
return rotateLeft(node);
}
return node;
}
Node* insert(Node* node, T key) {
if (!node) {
return new Node(key);
}
if (key < node->key) {
node->left = insert(node->left, key);
} else if (key > node->key) {
node->right = insert(node->right, key);
} else {
return node;
}
return balance(node);
}
Node* findMin(Node* node) {
return node->left ? findMin(node->left) : node;
}
Node* removeMin(Node* node) {
if (!node->left) {
return node->right;
}
node->left = removeMin(node->left);
return balance(node);
}
Node* remove(Node* node, T key) {
if (!node) {
return nullptr;
}
if (key < node->key) {
node->left = remove(node->left, key);
} else if (key > node->key) {
node->right = remove(node->right, key);
} else {
if (!node->left || !node->right) {
Node* temp = node->left ? node->left : node->right;
if (!temp) {
temp = node;
node = nullptr;
} else {
*node = *temp;
}
delete temp;
} else {
Node* temp = findMin(node->right);
node->key = temp->key;
node->right = removeMin(node->right);
}
}
if (!node) {
阅读全文