创建平衡二叉树
需要的辅助函数
- 创建树结点
- 计算每个节点高度
- 计算每个节点的平衡因子
- 插入新节点后对于出现的LL,RR,LR,RL型的子树处理问题
- 插入函数
- 构建一颗AVL平衡二叉树
本文章重点讲解第4个函数(在下文的step6,7,8,9)。
- 什么树不是平衡二叉树?
- 存在一个树节点的平衡因子绝对值大于1(平衡因子=左子树高度-右子树高度)
例:下图结点‘7‘的平衡因子为(左子树高度3-右子树高度1)=2
不是二叉平衡树
step1:定义树结点
typedef struct node
{
int height;
int data;
struct node *lchild,*rchild;
}node;
step2:创建树结点
node *newNode(int v)
{
node *Node=(node *)malloc(sizeof(node));
Node->data=v;
Node->height=1;
Node->lchild=Node->rchild=NULL;
return Node;
}
step3:取得树结点高度
int getHeight(node *root)
{
if(root==NULL) return 0;
else{
return root->height;
}
}
step4:得到树结点的平衡因子
int getBalancedFactor(node *root)
{
return getHeight(root->lchild)-getHeight(root->rchild);
}
step5:插入新结点后改变结点的高度(树结点的高度=max(左子树高度,右子树高度)+1)
void updateHeight(node *root){
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
step6:调整RR型的不平衡子树(如下图,画的不好凑合看~)
void L(node *&root)
{
node *temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
step7:调整RR型的不平衡子树
void R(node *&