AVL树(平衡二叉树)及其实现

来源:互联网 发布:学生空间七天网络答案 编辑:程序博客网 时间:2024/05/21 10:21

概念

AVL树是高度平衡的二叉排序树。
它的特点是:AVL树中任何节点的左右子树的高度差(平衡因子)的绝对值不大于1。
它需要每次在平衡因子不为0,-1,1时进行调整,使树的再次平衡。从而达到高效的查找。
点击这里:AVL的详细介绍


C++代码实现:

AVL树是特殊的二叉排序树,它的实现除了插入、删除操作外,其他的和平衡排序树相同,这里就不再实现,这里给出插入的算法。

#include <iostream>#include <algorithm>  // max(a, b)using namespace std;typedef struct AVLTreeNode{    int key;     // 结点的关键字     int height;  // 树的高度     AVLTreeNode *lChild, *rChild;  // 左右孩子 }*AVLTree;// 树高 int Height(const AVLTree &T){    return T ? T->height : 0;}// LL旋转 void LeftLeftRotation(AVLTree &T){    AVLTree lT = T->lChild;    T->lChild = lT->rChild;    lT->rChild = T;    T->height = max(Height(T->lChild), Height(T->rChild)) + 1;    lT->height = max(Height(lT->lChild), Height(lT->rChild)) + 1;    T = lT;}// RR旋转 void RightRightRotation(AVLTree &T){    AVLTree rT = T->rChild;    T->rChild = rT->lChild;    rT->lChild = T;    T->height = max(Height(T->lChild), Height(T->rChild)) + 1;    rT->height = max(Height(rT->lChild), Height(rT->rChild)) + 1;    T = rT;}// LR旋转void LeftRightRotation(AVLTree &T){    RightRightRotation(T->lChild);    LeftLeftRotation(T);}// RL旋转void RightLeftRotation(AVLTree &T){    LeftLeftRotation(T->rChild);    RightRightRotation(T);}// 插入结点 void Insert(AVLTree &T, const int &key){    if(!T){  // 为空树,新建结点作为根结点         T = new AVLTreeNode;        T->height = 1;        T->key = key;        T->lChild = T->rChild = NULL;    }    else if(key < T->key){  // key小于根结点关键字,则插入到左子树         Insert(T->lChild, key);        T->height = max(Height(T->lChild), Height(T->rChild)) + 1;        // 如果插入的新结点破坏了平衡,则进行调整         if(2 == Height(T->lChild) - Height(T->rChild)){            if(key < T->lChild->key){                LeftLeftRotation(T);            }            else{                LeftRightRotation(T);            }        }    }    else{  // key大于等于根结点关键字,则插入到右子树         Insert(T->rChild, key);        T->height = max(Height(T->lChild), Height(T->rChild)) + 1;        // 如果插入的新结点破坏了平衡,则进行调整         if(2 == Height(T->rChild) - Height(T->lChild)){            if(key < T->rChild->key){                RightLeftRotation(T);            }            else{                RightRightRotation(T);            }        }    }}// 中序遍历void InOrderTraverse(const AVLTree &T){    if(T){        InOrderTraverse(T->lChild);        cout << T->key << "(" << T->height << ") ";        InOrderTraverse(T->rChild);    }}int main(){    AVLTree T = NULL;    Insert(T, 1);    Insert(T, 3);    Insert(T, 5);    Insert(T, 7);    Insert(T, 9);    InOrderTraverse(T);    cout << endl;    Insert(T, 6);    InOrderTraverse(T);    cout << endl;    Insert(T, 0);    InOrderTraverse(T);    cout << endl;    return 0;}

运行结果:
这里写图片描述

所对应的二叉树:
这里写图片描述

0 0
原创粉丝点击