平衡二叉树的插入调整(C语言)
平衡二叉树的插入与调整
左右单旋
左右单旋
avltree Lrotation(avltree A) {
/*左单旋*/
avltree B = A->left;
A->left = B->right;
B->right = A;
A->height = getheight(A);
B->height = getheight(B);
return B;
}
avltree Rrotation(avltree A) {
/*右单旋*/
avltree B = A->right;
A->right = B->left;
B->left = A;
A->height = getheight(A);
B->height = getheight(B);
return B;
}
avltree LRrotation(avltree A) {
/*左右单旋*/
A->left = Rrotation(A->left);
return Lrotation(A);
}
avltree RLrotation(avltree A) {
A->right = Lrotation(A->right);
return Rrotation(A);
}
平衡二叉树的插入
插入后递归出栈,二叉树从插入点依次向上判定结点是否平衡
关键点在于判定插入数插在不平衡点的什么子树,才能决定使用哪种旋转函数,因此需要与不平衡点的子节点再次比较
avltree insert(avltree t, int num) {
if (!t) {
t = (avltree)malloc(sizeof(struct treenode));
t->data = num;
t->left = NULL;
t->right = NULL;
t->height = 0;
} /*叶节点高为0*/
else {
if (num < t->data) {
t->left = insert(t->left, num);
if (getheight(t->left) - getheight(t->right) == 2)
{
if (num < t->left->data) t = Lrotation(t); /*插入左子树的左子树左单旋*/
else t = LRrotation(t);
}
} /*左子树插入并调整平衡*/
else if (num > t->data) {
t->right = insert(t->right, num);
if (getheight(t->right) - getheight(t->left) == 2)
{
if (num > t->right->data) t = Rrotation(t); /*插入右子树的右子树左单旋*/
else t = RLrotation(t);
}
}/*右子树插入并调整平衡*/
}
t->height = getheight(t);/*更新树高*/
return t;
}
求树高函数
默认叶节点高度为0
typedef struct treenode *avltree;
struct treenode {
avltree left;
avltree right;
int data;
int height;
};
int max(int a, int b) {
return (a > b ? a : b);
}
int getheight(avltree t) {
/*求树高*/
if (!t) return -1;
else {
int lheight = getheight(t->left);
int rheight = getheight(t->right);
return max(lheight, rheight) + 1;
}
}