Rotazione a sinistra
Lezione 8 di 16 del corso Albero AVL - Serie sulle strutture dati #10 di Coddy.
Una rotazione sinistra è l’immagine speculare della rotazione destra che hai appena scritto, usata quando il lato destro di un nodo è troppo alto. Chiama il nodo sbilanciato x e il suo figlio destro y. y diventa la nuova radice del sottoalbero, x diventa il figlio sinistro di y e il vecchio sottoalbero sinistro di y (T2) viene riattaccato come nuovo figlio destro di x.
La stessa regola vale per le altezze: ricalcola prima x, poi y, poiché ora x è il nodo più basso.
Sfida
FacileScrivi un metodo rotateLeft(x) su AVLTree. Sia y = x.right e T2 = y.left. Imposta y.left = x e x.right = T2, ricalcola l’height di x e poi di y, quindi restituisci y come nuova radice del sottoalbero.
Provalo tu
#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;
}
Tutte le lezioni di Albero AVL - Serie sulle strutture dati #10
2Progetto sugli alberi AVL
Classe NodoClasse AVLTreeEsercitati da solo: Compilatore C online