左旋
Coddy AVL 树:数据结构系列 #10 课程的第 8 课,共 16 课。
左旋转是你刚写的右旋转的镜像,用于节点右侧过高的情况。将不平衡节点称为 x,将它的右子节点称为 y。y 会成为新的子树根节点,x 会成为 y 的左子节点,而 y 原来的左子树(T2)会重新接到 x 上,成为它新的右子树。
高度也按同样的规则处理:先重新计算 x,再计算 y,因为 x 现在是较低的节点。
挑战
简单在 AVLTree 上编写方法 rotateLeft(x)。令 y = x.right,并令 T2 = y.left。设置 y.left = x 和 x.right = T2,先重新计算 x 的 height,再重新计算 y 的 height,然后返回 y 作为新的子树根节点。
亲手试试
#include <stdio.h>
#include <string.h>
#include "avltree.h"
int main(void) {
AVLTree* tree = AVLTree_create();
char line[256];
while (fgets(line, sizeof(line), stdin) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (strcmp(line, "1") == 0) {
Node* x = Node_create(10);
x->height = 3;
Node* y = Node_create(20);
y->height = 2;
Node* t2 = Node_create(30);
t2->height = 1;
y->right = t2;
x->right = y;
Node* newRoot = AVLTree_rotateLeft(tree, x);
printf("%d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value);
}
if (strcmp(line, "2") == 0) {
Node* x = Node_create(20);
x->height = 3;
Node* y = Node_create(40);
y->height = 2;
y->left = Node_create(30);
y->left->height = 1;
y->right = Node_create(50);
y->right->height = 1;
x->left = Node_create(10);
x->left->height = 1;
x->right = y;
Node* newRoot = AVLTree_rotateLeft(tree, x);
printf("%d %d %d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value, newRoot->left->left->value, newRoot->left->right->value);
}
}
return 0;
}
AVL 树:数据结构系列 #10中的所有课
自己练习: C 在线编译器