AVL树的实现(C++)

Implement of AVL_Tree using Cpp

Introduction

AVL_tree是平衡二叉树的一种,能够自动维持平衡。维持平衡的方式则是通过单旋转与双旋转来实现。AVL_Tree规定了子节点的高度相差不超过1,大于等于2时,对树进行调节,使之重新符合要求。
二叉树中,不平衡的情况主要可以分为四种,本质上其实是两种:
L
R
- 上图中, root 是根节点,后缀 R L 分别代表父节点的左右子节点。
- h 代表本节点的高度,当某个分支比另外一个分支高2时,可以分为四种情况:
-

Rh<Lh{1. LLh=2 (LL is the left child of L )2. LR
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AVL是一种自平衡二叉搜索,它的每个节点存储一个键值对,且每个节点的左子和右子的高度差不超过1。这种平衡特性使得AVL在查找、插入和删除操作方面都有很好的性能表现。 下面是一个简单的AVL的C++实现: ```c++ #include <iostream> using namespace std; // AVL节点 struct Node { int key; int height; Node *left; Node *right; Node(int k) : key(k), height(1), left(NULL), right(NULL) {} }; // 获取节点高度 int height(Node *node) { if (node == NULL) { return 0; } return node->height; } // 获取节点平衡因子 int balanceFactor(Node *node) { if (node == NULL) { return 0; } return height(node->left) - height(node->right); } // 更新节点高度 void updateHeight(Node *node) { node->height = max(height(node->left), height(node->right)) + 1; } // 右旋操作 Node* rightRotate(Node *node) { Node *leftChild = node->left; Node *rightChild = leftChild->right; leftChild->right = node; node->left = rightChild; updateHeight(node); updateHeight(leftChild); return leftChild; } // 左旋操作 Node* leftRotate(Node *node) { Node *rightChild = node->right; Node *leftChild = rightChild->left; rightChild->left = node; node->right = leftChild; updateHeight(node); updateHeight(rightChild); return rightChild; } // 插入节点 Node* insert(Node *node, int key) { if (node == NULL) { 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; } updateHeight(node); int bf = balanceFactor(node); if (bf > 1) { if (balanceFactor(node->left) >= 0) { return rightRotate(node); } else { node->left = leftRotate(node->left); return rightRotate(node); } } else if (bf < -1) { if (balanceFactor(node->right) <= 0) { return leftRotate(node); } else { node->right = rightRotate(node->right); return leftRotate(node); } } return node; } // 中序遍历AVL void inOrder(Node *node) { if (node == NULL) { return; } inOrder(node->left); cout << node->key << " "; inOrder(node->right); } int main() { Node *root = NULL; root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); inOrder(root); cout << endl; return 0; } ``` 在上面的实现中,我们使用了递归插入节点,并在插入节点后更新了节点的高度和平衡因子。当节点的平衡因子大于1或小于-1时,我们进行相应的旋转操作来保持的平衡。最后,我们在main函数中插入一些节点,并进行中序遍历来检查是否正确构建。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值