Rotación a la derecha
Lección 7 de 16 del curso Árbol AVL - Serie de Estructuras de Datos #10 de Coddy.
Cuando el lado izquierdo de un nodo es demasiado alto, una rotación a la derecha lo soluciona. Llamemos al nodo desequilibrado y y a su hijo izquierdo x. La rotación promueve a x para que tome el lugar de y: x se convierte en la nueva raíz del subárbol, y se convierte en el hijo derecho de x, y el antiguo subárbol derecho de x (llamémoslo T2) se vuelve a conectar como el nuevo hijo izquierdo de y, ya que cada valor en T2 sigue siendo mayor que x y menor que y.
Después de volver a vincular los punteros, tanto y como x necesitan que se recalcule su height, y primero ya que ahora está más abajo en el árbol.
Desafío
FácilEscribe un método rotateRight(y) en AVLTree. Sea x = y.left y T2 = x.right. Establece x.right = y y y.left = T2, vuelve a calcular la height de y luego x como 1 + max(getHeight(left), getHeight(right)), y devuelve x como la nueva raíz del subárbol.
Pruébalo tú mismo
#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;
}
Todas las lecciones de Árbol AVL - Serie de Estructuras de Datos #10
2Proyecto de Árbol AVL
Clase NodoClase AVLTree