Menu
Coddy logo textTech

Rotação à Direita

Lição 7 de 16 do curso Árvore AVL - Série de Estruturas de Dados #10 da Coddy.

Quando o lado esquerdo de um nó está muito alto, uma rotação à direita o corrige. Chame o nó desbalanceado de y e seu filho à esquerda de x. A rotação promove x para ocupar o lugar de y: x torna-se a nova raiz da subárvore, y torna-se o filho à direita de x, e a antiga subárvore à direita de x (chame-a de T2) é anexada como o novo filho à esquerda de y, já que cada valor em T2 ainda é maior que x e menor que y.

Após relincar os ponteiros, tanto y quanto x precisam ter sua height recalculada, y primeiro, pois agora está em uma posição inferior na árvore.

challenge icon

Desafio

Fácil

Escreva um método rotateRight(y) em AVLTree. Seja x = y.left e T2 = x.right. Defina x.right = y e y.left = T2, recalcule a height de y e depois de x como 1 + max(getHeight(left), getHeight(right)), e retorne x como a nova raiz da subárvore.

Experimente você mesmo

#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 as lições de Árvore AVL - Série de Estruturas de Dados #10