左回転
Coddyの「AVL Tree - データ構造シリーズ #10」コースのレッスン 8/16。
左回転は、先ほど作成した右回転の鏡像であり、ノードの右側が高くなりすぎた場合に使用されます。不均衡なノードを x、その右の子を y と呼びます。y が新しい部分木の根になり、x は y の左の子になり、y の元の左部分木(T2)は x の新しい右の子として再配置されます。
高さについても同じルールが適用されます。x は現在下位のノードであるため、まず x を再計算し、次に y を再計算します。
チャレンジ
簡単AVLTree にメソッド rotateLeft(x) を記述してください。y = x.right および T2 = y.left とします。y.left = x および x.right = T2 を設定し、x 次に 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;
}