在AVL树的删除操作中,需要重新平衡树以确保树的平衡性。在节点删除后,需要从被删除节点的父节点开始向上遍历,检查子树的平衡因子是否失衡,并进行旋转操作以保持平衡。同时,在进行旋转操作时需要更新节点的高度信息。
下面是一个AVL树的删除操作的示例代码(假设节点类型为Node,节点高度信息在节点结构体中的height属性中存储):
Node* deleteNode(Node* root, int key) {
if (!root) return NULL;
if (key < root->val) {
root->left = deleteNode(root->left, key);
} else if (key > root->val) {
root->right = deleteNode(root->right, key);
} else {
if (!root->left || !root->right) {
Node* tmp = root->left ? root->left : root->right;
if (!tmp) {
tmp = root;
root = NULL;
} else {
*root = *tmp;
}
delete tmp;
} else {
Node* cur = root->right;
while (cur->left) {
cur = cur->left;
}
root->val = cur->val;
root->right = deleteNode(root->right, cur->val);
}
}
if (!root) return NULL;
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
int balance = getBalanceFactor(root);
if (balance > 1 && getBalanceFactor(root->left) >= 0) {
return rightRotate(root);
}
if (balance > 1 && getBalanceFactor(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalanceFactor(root->right) <= 0) {
return leftRotate(root);
}
if (balance < -1 && getBalanceFactor(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
上一篇:AVL树删除 C++