Rotação à Esquerda
Lição 8 de 16 do curso Árvore AVL - Série de Estruturas de Dados #10 da Coddy.
Uma rotação à esquerda é a imagem espelhada da rotação à direita que você acabou de escrever, usada quando o lado direito de um nó está muito alto. Chame o nó desbalanceado de x e seu filho direito de y. y se torna a nova raiz da subárvore, x se torna o filho esquerdo de y, e a antiga subárvore esquerda de y (T2) é reanexada como o novo filho direito de x.
Mesma regra para as alturas: recalcule x primeiro, depois y, já que x agora é o nó inferior.
Desafio
FácilEscreva um método rotateLeft(x) em AVLTree. Seja y = x.right e T2 = y.left. Defina y.left = x e x.right = T2, recalcule a height de x e depois de y, e retorne y 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* 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 as lições de Árvore AVL - Série de Estruturas de Dados #10
2Projeto de Árvore AVL
Classe NóClasse AVLTree