平衡二叉树是带有平衡条件的二叉查找树,指的是空树或者任一结点左、右高度差的绝对值不超过1的二叉树.
比如:
实现的难点在于,二叉树的平衡旋转
分为四种旋转,RR、LL、LR、RL旋转
RR旋转
麻烦结点在发现者右子树的右边,所以叫RR插入,需要RR旋转
LL旋转
麻烦结点在发现者左子树的左边,所以叫LL插入,需要LL旋转
LR旋转
RL旋转
C/C++实现
#include <stack>//栈
#include <queue>
#include <iostream>
#include <initializer_list>
using namespace std;
template <typename Comparable>
class AVLTree
{
private:
static const int ALLOWED_IMBLANCE = 1;
struct AVLNode
{
Comparable element;
AVLNode * left;
AVLNode * right;
int height;
AVLNode(const Comparable & theElement, AVLNode *lt, AVLNode *rt,int h = 0)
:element(theElement), left(lt), right(rt),height(h) {
}
AVLNode(Comparable && theElement, AVLNode *lt, AVLNode *rt, int h = 0)
:element(std::move(theElement)), left(lt), right(rt),height(h) {
}
};
AVLNode * root;
void Insert(const Comparable &x, AVLNode * & t);
void Insert(Comparable && x, AVLNode *&t);
void Insert(initializer_list<Comparable> &d, AVLNode *& t);
void Remove(const Comparable &x, AVLNode *&t);
AVLNode * findMin(AVLNode *t)const;
AVLNode * findMax(AVLNode *t)const;
bool contains(const Comparable &x, AVLNode *t) const;
void makeEmpty(AVLNode * &t);
void PrintTree(AVLNode *t) const;
AVLNode* clone(AVLNode *t)const
{
if (t == nullptr)
return nullptr;
return new AVLNode(t->element, clone(t->left), clone(t->right));
}
void rotateWithLeftChild(AVLNode *& k2);
void rotateWithRightChild(AVLNode *& k2);
void doubleWithLeftChild(AVLNode *&k3);
void doubleWithRightChild(AVLNode *&k3);
void balance(AVLNode*& t);
public:
AVLTree() :root(nullptr) {
}
AVLTree(const AVLTree & rhs) :root(nullptr) {
root = clone(rhs.root); }
AVLTree(AVLTree && rhs) :root(nullptr) {
root = rhs.root;rhs = nullptr;}
~AVLTree() {
makeEmpty(); }
const Comparable & findMin() const {
return findMin(root)->element; }
const Comparable & findMax() const {
findMax(root)->element; }
bool contains(const Comparable & x) const {
return contains(x, root); }
bool isEmpty() const {
return root == nullptr; }
int height(AVLNode *t) const {
return t == nullptr ? -1 : t->height; }
void PrintTree()const {
PrintTree(root); }
void makeEmpty() {
makeEmpty(root); }
void Insert(const Comparable &x) {
Insert(x,root); }
void Insert(Comparable && x) {
Insert(x,root); }
void Insert(initializer_list<Comparable>d) {
Insert(d, root); }
void Remove(const Comparable &x) {
Remove(x, root); }
AVLTree & operator=(const AVLTree & rhs)
{
if (this != &rhs)
{
makeEmpty();
root = clone(rhs.