Right Rotate
Lesson 7 of 16 in Coddy's AVL Tree - Data Structures Series #10 course.
When a node's left side is too tall, a right rotation fixes it. Call the unbalanced node y and its left child x. The rotation promotes x to take y's place: x becomes the new subtree root, y becomes x's right child, and x's old right subtree (call it T2) is reattached as y's new left child, since every value in T2 is still greater than x and less than y.
After relinking the pointers, both y and x need their height recomputed, y first since it is now lower in the tree.
Challenge
EasyWrite a method rotateRight(y) on AVLTree. Let x = y.left and T2 = x.right. Set x.right = y and y.left = T2, recompute the height of y then x as 1 + max(getHeight(left), getHeight(right)), and return x as the new subtree root.
Try it yourself
#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;
}
All lessons in AVL Tree - Data Structures Series #10
2AVL Tree Project
Node ClassAVLTree Class