AVL树(平衡二叉树)详解 | C/C++实现

性质

在BST树的基础上引入了平衡因子的概念,要求任意一个节点的左右子树高度差不超过1

需要旋转的四种情况
  • 左孩子左子树太高:右旋
  • 右孩子右子树太高:左旋
  • 左孩子右子树太高:先对左孩子左旋,再对当前节点右旋(左平衡)
  • 右孩子左子树太高:先对右孩子右旋,再对当前节点左旋(右平衡)
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

// 定义节点类型
template<typename T>
struct Node {
    Node(T data = T()) : data_(data), left_(nullptr), right_(nullptr), height_(1) {}
    T data_;
    Node* left_;
    Node* right_;
    int height_; // 记录节点的高度
};

// AVL树
template<typename T>
class AVLTree {
public:
    AVLTree() : root_(nullptr) {}
    // 插入
    void insert(const T& val) {
        root_ = insert(root_,val);
    }
    // 删除
    void remove(const T& val) {
        root_ = remove(root_,val);
    }
private:
    Node<T>* root_; // 根节点
    // 返回节点的高度
    int height(Node<T> *node) {
        return node == nullptr ? 0 : node->height_;
    }
    // 右旋
    Node<T>* rightRotate(Node<T>* node);
    // 左旋
    Node<T>* leftRotate(Node<T>* node);
    // 左平衡
    Node<T>* leftBalance(Node<T>* node);
    // 右平衡
    Node<T>* rightBalance(Node<T>* node);
    // 插入
    Node<T>* insert(Node<T>* node, const T& val);
    // 删除
    Node<T>* remove(Node<T>* node, const T& val);
};

// 右旋
template<typename T>
Node<T>* AVLTree<T>::rightRotate(Node<T>* node) {
    // 节点旋转
    Node<T>* child = node->left_;
    node->left_ = child->right_;
    child->right_ = node;
    // 高度更新
    node->height_ = max(height(node->left_), height(node->right_)) + 1;
    child->height_ = max(height(child->left_), height(child->right_)) + 1;
    // 返回旋转后的子树的新根节点
    return child;
}

// 左旋
template<typename T>
Node<T>* AVLTree<T>::leftRotate(Node<T>* node) {
    // 节点旋转
    Node<T> *child = node->left_;
    node->right_ = child->left_;
    child->left_ = node;
    // 高度更新
    node->height_ = max(height(node->left_), height(node->right_)) + 1;
    child->height_ = max(height(child->left_), height(child->right_)) + 1;
    // 返回旋转后的子树的新根节点
    return child;
}

// 左平衡 先对node的左子树左旋,再对node右旋
template<typename T>
Node<T>* AVLTree<T>::leftBalance(Node<T> *node) {
    node->left_ = leftRotate(node->left_);
    return rightRotate(node);
}

// 右平衡 先对node的右子树右旋,再对node左旋
template<typename T>
Node<T>* AVLTree<T>::rightBalance(Node<T> *node) {
    node->right_ = rightRotate(node->right_);
    return leftRotate(node);
}

// 插入
template<typename T>
Node<T>* AVLTree<T>::insert(Node<T> *node, const T &val) {
    // 递归结束 找到插入的位置
    if (node == nullptr) return new Node<T>(val);

    if (node->data_ > val) {
        node->left_ = insert(node->left_,val);
        // 判断是否失衡
        if (height(node->left_) - height(node->right_) > 1) {
            if (height(node->left_->left_) >= height(node->left_->right_)) {
                // 左孩子的左子树太高
                node = rightRotate(node);
            } else {
                // 左孩子的右子树太高
                node = leftBalance(node);
            }
        }
    } else if (node->data_ < val) {
        node->right_ = insert(node->right_,val);
        if (height(node->right_) - height(node->left_) > 1) {
            if (height(node->right_->right_) >= height(node->right_->left_)) {
                node = leftRotate(node);
            } else {
                node = rightBalance(node);
            }
        }
    } else {
        // 找到相同节点 不需要向下递归 直接向上回溯
    }

    // 因为子树添加了新的节点 所以在递归的时候需要更新节点高度
    node->height_ = max(height(node->left_), height(node->right_)) + 1;

    return node;
}

// 删除操作 从叶子节点中选出一个节点 进行替换
template<typename T>
Node<T>* AVLTree<T>::remove(Node<T> *node, const T &val) {
    if (node == nullptr) {
        return nullptr;
    }

    if (node->data_ > val) {
        node->left_ = remove(node->left_,val);
        if (height(node->right_) - height(node->left_) > 1) {
            if (height(node->right_->right_) >= height(node->right_->left_)) {
                node = leftRotate(node);
            } else {
                node = rightBalance(node);
            }
        }
    } else if (node->data_ < val) {
        node->right_ = remove(node->right_,val);
        if (height(node->left_) - height(node->right_) > 1) {
            if (height(node->left_->left_) >= height(node->left_->right_)) {
                node = rightRotate(node);
            } else {
                node = leftBalance(node);
            }
        }
    } else {
        // 找到节点
        // 如果有两个孩子
        if (node->left_ != nullptr && node->right_ != nullptr) {
            // 谁高删谁的节点
            if (height(node->left_) >= height(node->right_)) {
                Node<T>* pre = node->left_;
                while (pre->right_ != nullptr) {
                    pre = pre->right_;
                }
                node->data_ = pre->data_;
                node->left_ = remove(node->left_,pre->data_);
            } else {
                Node<T>* pre = node->right_;
                while (pre->left_ != nullptr) {
                    pre = pre->left_;
                }
                node->data_ = pre->data_;
                node->right_ = remove(node->right_,pre->data_);
            }
        } else {
            // 如果只有一个孩子
            if (node->left_ != nullptr) {
                Node<T>* left = node->left_;
                delete node;
                return left;
            } else if (node->right_ != nullptr) {
                Node<T>* right = node->right_;
                delete node;
                return right;
            } else {
                delete node;
                return nullptr;
            }
        }
    }

    // 更新节点高度
    node->height_ = max(height(node->left_), height(node->right_)) + 1;
    return node;
}

性能分析

  • AVL树插入一个节点最多只需要两次旋转就可以恢复平衡

插入一个节点会导致节点所在的子树高度加1,但是旋转会让新节点所在子树减1,所以AVL树插入一个节点最多只需要两次旋转就可以了

  • AVL树删除一个节点最多需要O(logN)次旋转才可以恢复平衡

删除一个节点会导致节点所在子树减1,旋转又会让节点所在的子树减1,所以最坏的时候需要O(logN)次旋转

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K38jGI6Q-1678955045720)(C:\Users\gnezd\AppData\Roaming\Typora\typora-user-images\image-20230316155305771.png)]

删除节点 X 之后,R4的平衡因子变为 -2,R4 左旋;R3 的平衡因子变为 2,R3 右旋;R2 的平衡因子变为 -2, R2左旋;R1的平衡因子变为2,R1 右旋

当从根节点至待删除节点的父节点平衡因子交替为 -1 和 +1,删除该节点一旦触发旋转就需要logn次旋转

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
平衡二叉树是一种特殊的二叉树,它的左右子树的高度差不超过1。AVL树是一种自平衡的二叉搜索树,它的高度始终保持在O(log n)。 下面是C语言实现平衡二叉树AVL树)的代码: ``` #include <stdio.h> #include <stdlib.h> /* 定义平衡二叉树节点结构体 */ struct AVLNode { int data; // 存储的数据 int height; // 节点高度 struct AVLNode *leftChild; // 左子树 struct AVLNode *rightChild; // 右子树 }; /* 获取节点高度 */ int getHeight(struct AVLNode *node) { if (node == NULL) { return -1; } else { return node->height; } } /* 获取节点平衡因子 */ int getBalanceFactor(struct AVLNode *node) { if (node == NULL) { return 0; } else { return getHeight(node->leftChild) - getHeight(node->rightChild); } } /* 更新节点高度 */ void updateHeight(struct AVLNode *node) { node->height = 1 + (getHeight(node->leftChild) > getHeight(node->rightChild) ? getHeight(node->leftChild) : getHeight(node->rightChild)); } /* 右旋操作 */ struct AVLNode *rotateRight(struct AVLNode *node) { struct AVLNode *newRoot = node->leftChild; node->leftChild = newRoot->rightChild; newRoot->rightChild = node; updateHeight(node); updateHeight(newRoot); return newRoot; } /* 左旋操作 */ struct AVLNode *rotateLeft(struct AVLNode *node) { struct AVLNode *newRoot = node->rightChild; node->rightChild = newRoot->leftChild; newRoot->leftChild = node; updateHeight(node); updateHeight(newRoot); return newRoot; } /* 插入操作 */ struct AVLNode *insert(struct AVLNode *root, int data) { if (root == NULL) { root = (struct AVLNode *) malloc(sizeof(struct AVLNode)); root->data = data; root->height = 0; root->leftChild = NULL; root->rightChild = NULL; } else if (data < root->data) { root->leftChild = insert(root->leftChild, data); if (getHeight(root->leftChild) - getHeight(root->rightChild) == 2) { if (data < root->leftChild->data) { root = rotateRight(root); } else { root->leftChild = rotateLeft(root->leftChild); root = rotateRight(root); } } } else if (data > root->data) { root->rightChild = insert(root->rightChild, data); if (getHeight(root->rightChild) - getHeight(root->leftChild) == 2) { if (data > root->rightChild->data) { root = rotateLeft(root); } else { root->rightChild = rotateRight(root->rightChild); root = rotateLeft(root); } } } updateHeight(root); return root; } /* 中序遍历 */ void inOrderTraversal(struct AVLNode *root) { if (root != NULL) { inOrderTraversal(root->leftChild); printf("%d ", root->data); inOrderTraversal(root->rightChild); } } int main() { struct AVLNode *root = NULL; int data[] = {5, 2, 8, 1, 3, 6, 9}; int len = sizeof(data) / sizeof(data[0]); int i; for (i = 0; i < len; i++) { root = insert(root, data[i]); } inOrderTraversal(root); return 0; } ``` 以上代码实现平衡二叉树的插入和中序遍历操作。在插入操作中,根据插入节点的值和当前节点的值的大小关系,不断递归向左或向右子树进行插入操作,并在递归返回时更新节点高度和进行平衡操作。在平衡操作中,根据节点的平衡因子进行旋转操作,使树重新平衡。在中序遍历操作中,按照左子树、根节点、右子树的顺序遍历树中的节点,输出节点的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值