下面是一个示例的AVL树删除的C++代码:
#include
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
int height;
};
int max(int a, int b) {
return (a > b) ? a : b;
}
int getHeight(Node* node) {
if (node == NULL)
return 0;
return node->height;
}
Node* newNode(int data) {
Node* node = new Node();
node->data = data;
node->left = NULL;
node->right = NULL;
node->height = 1;
return node;
}
Node* rotateRight(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
x->height = 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 = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
int getBalance(Node* node) {
if (node == NULL)
return 0;
return getHeight(node->left) - getHeight(node->right);
}
Node* insert(Node* node, int data) {
if (node == NULL)
return newNode(data);
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
else
return node;
node->height = 1 + max(getHeight(node->left), getHeight(node->right));
int balance = getBalance(node);
if (balance > 1 && data < node->left->data)
return rotateRight(node);
if (balance < -1 && data > node->right->data)
return rotateLeft(node);
if (balance > 1 && data > node->left->data) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}
if (balance < -1 && data < node->right->data) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}
return node;
}
Node* minValueNode(Node* node) {
Node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
Node* deleteNode(Node* root, int data) {
if (root == NULL)
return root;
if (data < root->data)
root->left = deleteNode(root->left, data);
else if (data > root->data)
root->right = deleteNode(root->right, data);
else {
if ((root->left == NULL) || (root->right == NULL)) {
Node* temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
}
else
*root = *temp;
free(temp);
}
else {
Node* temp = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
}
if (root == NULL)
return root;
root->height = 1 + max(getHeight(root->left), getHeight(root->right));
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rotateRight(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = rotateLeft(root->left);
return rotateRight(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return rotateLeft(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rotateRight(root->right);
return rotateLeft(root);
}
return root;
}
void preOrder(Node* root) {
if (root != NULL) {
cout << root->data << " ";