Menu
Coddy logo textTech

Rotación a la izquierda

Lección 8 de 16 del curso Árbol AVL - Serie de Estructuras de Datos #10 de Coddy.

Una rotación a la izquierda es la imagen especular de la rotación a la derecha que acabas de escribir, utilizada cuando el lado derecho de un nodo es demasiado alto. Llama al nodo desequilibrado x y a su hijo derecho y. y se convierte en la nueva raíz del subárbol, x se convierte en el hijo izquierdo de y, y el antiguo subárbol izquierdo de y (T2) se vuelve a unir como el nuevo hijo derecho de x.

La misma regla para las alturas: vuelve a calcular x primero, luego y, ya que x es ahora el nodo inferior.

challenge icon

Desafío

Fácil

Escribe un método rotateLeft(x) en AVLTree. Sea y = x.right y T2 = y.left. Establece y.left = x y x.right = T2, vuelve a calcular la height de x luego la de y, y devuelve y 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* 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;
}

Todas las lecciones de Árbol AVL - Serie de Estructuras de Datos #10