Rechtsrotation
Lektion 7 von 16 im Kurs AVL-Baum - Datenstrukturen-Serie #10 von Coddy.
Wenn die linke Seite eines Knotens zu hoch ist, behebt eine Rechtsrotation dies. Nennen wir den unbalancierten Knoten y und sein linkes Kind x. Die Rotation befördert x an die Stelle von y: x wird die neue Wurzel des Teilbaums, y wird das rechte Kind von x, und der alte rechte Teilbaum von x (nennen wir ihn T2) wird als neues linkes Kind von y wieder angehängt, da jeder Wert in T2 immer noch größer als x und kleiner als y ist.
Nach dem Neuverknüpfen der Pointer müssen sowohl für y als auch für x die height neu berechnet werden, wobei y zuerst an der Reihe ist, da es sich nun weiter unten im Baum befindet.
Aufgabe
EinfachSchreiben Sie eine Methode rotateRight(y) für AVLTree. Sei x = y.left und T2 = x.right. Setzen Sie x.right = y und y.left = T2, berechnen Sie die height von y und dann von x neu als 1 + max(getHeight(left), getHeight(right)) und geben Sie x als die neue Wurzel des Teilbaums zurück.
Probier es selbst
#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* y = Node_create(30);
y->height = 3;
Node* x = Node_create(20);
x->height = 2;
Node* t1 = Node_create(10);
t1->height = 1;
x->left = t1;
y->left = x;
Node* newRoot = AVLTree_rotateRight(tree, y);
printf("%d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value);
}
if (strcmp(line, "2") == 0) {
Node* y = Node_create(50);
y->height = 3;
Node* x = Node_create(30);
x->height = 2;
x->left = Node_create(20);
x->left->height = 1;
x->right = Node_create(40);
x->right->height = 1;
y->left = x;
y->right = Node_create(60);
y->right->height = 1;
Node* newRoot = AVLTree_rotateRight(tree, y);
printf("%d %d %d %d %d %d\n", newRoot->value, newRoot->height, newRoot->left->value, newRoot->right->value, newRoot->right->left->value, newRoot->right->right->value);
}
}
return 0;
}