目录
平衡二叉树定义
为了使二叉排序树的平均查找长度更小,需要适当控制树高,显然,控制树高的一个有效措施就是尽量保持树的左右子树高度大致平衡,由此产生了平衡二叉树的概念。
G . M . A d e l s o n − V e l s k i i G.M.Adelson-Velskii G.M.Adelson−Velskii和 E . M . L a n d i s E.M.Landis E.M.Landis在1962年提出了一种平衡二叉树模型,故称为 A V L AVL AVL树。在未声明的情况下,平衡二叉树默认指 A V L 树 AVL树 AVL树。
A V L AVL AVL树是一棵二叉排序树,其或者为空,或者满足以下性质:
1)左右子树高度差的绝对值不大于1
2)左右子树都是平衡二叉树
定义平衡因子来研究AVL树:
结点的平衡因子 B F BF BF=结点的左子树高度-结点右子树高度
A V L AVL AVL树类的封装
struct BBTNode
{
BBTNode*leftson;
BBTNode*rightson;
BBTNode*parent;
int data;
BBTNode(BBTNode*node1,BBTNode*node2,BBTNode*node3)
{
leftson = node1;
rightson = node2;
parent = node3;
}
};
class BBT
{
public:
BBT(int num);
~BBT();
void preorder();
void insert(int element);
bool find(int elemnet);
void del(int element);
void delall();
protected:
void insert(int element, BBTNode*&node, BBTNode*&parent);
int getB_factor(BBTNode*node);
int getheight(BBTNode*node);
void LL(BBTNode*&node);
void LR(BBTNode*&node);
void RR(BBTNode*&node);
void RL(BBTNode*&node);
void preorder(BBTNode*node);
bool find(int element, BBTNode* node);
void del(int element, BBTNode*&node);
void del_directly(BBTNode*&node);
void del_repalce(BBTNode*&node, BBTNode*&son);
void del_reconnect(BBTNode*&node);
void adjust(BBTNode*&node);
void delall(BBTNode*&node);
private:
BBTNode* root;
int num;
};
A V L AVL AVL树的插入操作与平衡化
A V L AVL AVL树的平衡因子为-1,0或1,设计平衡二叉树操作算法的关键在于如何使得平衡二叉树保持平衡。以下四种情况下的插入操作可能会导致原有 A V L AVL AVL树发生不平衡:
- (1) L L LL LL:若某一结点的平衡因子为1,当在其左子树的左子树上插入一个新结点时会导致该结点的平衡因子由1变为2
- (2) R R RR RR:若某一节点的平衡因子为-1,当在其右子树的右子树上插入一个新结点会导致该结点的平衡因子由-1变为-2
- (3) L R LR LR:若某一结点的平衡因子为1,当在其左子树的右子树上插入一个新结点时会导致该结点的平衡因子由1变为2
- (4) R